|
| 1 | +// https://leetcode.com/problems/search-in-rotated-sorted-array/ |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public int search(int[] nums, int target) { |
| 5 | + int n= nums.length; |
| 6 | + int start= 0; |
| 7 | + int end= n-1; |
| 8 | + int mid= (start+end)/2; |
| 9 | + |
| 10 | + // Base Cases: |
| 11 | + |
| 12 | + // 1. If length of array is 1 |
| 13 | + if(n == 1){ |
| 14 | + if(nums[0] == target){ |
| 15 | + return 0; |
| 16 | + } |
| 17 | + return -1; |
| 18 | + } |
| 19 | + |
| 20 | + // 2. If length of array is 2 |
| 21 | + if(n == 2){ |
| 22 | + if(nums[0] == target){ |
| 23 | + return 0; |
| 24 | + } |
| 25 | + else if(nums[1] == target){ |
| 26 | + return 1; |
| 27 | + } |
| 28 | + return -1; |
| 29 | + } |
| 30 | + |
| 31 | + // 3. If the array is not rotated |
| 32 | + if(nums[n-1] > nums[0]){ |
| 33 | + return binarySearch(nums, 0, n-1, target); |
| 34 | + } |
| 35 | + |
| 36 | + boolean status= false; |
| 37 | + int rotateIndex= -1; |
| 38 | + |
| 39 | + // Finding the index where rotation has taken place |
| 40 | + while(start<= end){ |
| 41 | + mid= (start+end)/2; |
| 42 | + |
| 43 | + if(nums[mid-1] > nums[mid]){ |
| 44 | + if(mid+1 >= n){ |
| 45 | + rotateIndex= mid; |
| 46 | + break; |
| 47 | + } |
| 48 | + |
| 49 | + if( mid+1 < n && nums[mid] < nums[mid+1]){ |
| 50 | + rotateIndex= mid; |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // Base Case (If start+1 == end) |
| 56 | + // In this case mid value won't update |
| 57 | + if(start+1 == end){ |
| 58 | + start= end; |
| 59 | + mid= (start+end)/2; |
| 60 | + } |
| 61 | + |
| 62 | + if(nums[start] > nums[mid]){ |
| 63 | + // Discarding the right subarray |
| 64 | + end= mid; |
| 65 | + } |
| 66 | + else{ |
| 67 | + // Discarding the left subarray |
| 68 | + start= mid; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + if(target > nums[n-1]){ |
| 73 | + return binarySearch(nums, 0, rotateIndex, target); |
| 74 | + } |
| 75 | + else{ |
| 76 | + return binarySearch(nums, rotateIndex, n-1, target); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + public int binarySearch(int[] nums, int start, int end, int target){ |
| 81 | + int mid= (start+end)/2; |
| 82 | + |
| 83 | + while(start<= end){ |
| 84 | + mid= (start+end)/2; |
| 85 | + |
| 86 | + if(nums[mid] == target){ |
| 87 | + return mid; |
| 88 | + } |
| 89 | + |
| 90 | + if(nums[mid] > target){ |
| 91 | + end= mid-1; |
| 92 | + } |
| 93 | + else{ |
| 94 | + start= mid+1; |
| 95 | + } |
| 96 | + } |
| 97 | + return -1; |
| 98 | + } |
| 99 | +} |
0 commit comments