|
| 1 | +Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. |
| 2 | + |
| 3 | +(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). |
| 4 | + |
| 5 | +You are given a target value to search. If found in the array return its index, otherwise return -1. |
| 6 | + |
| 7 | +You may assume no duplicate exists in the array. |
| 8 | + |
| 9 | +Your algorithm's runtime complexity must be in the order of O(log n). |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +
|
| 13 | +Input: nums = [4,5,6,7,0,1,2], target = 0 |
| 14 | +Output: 4 |
| 15 | +Example 2: |
| 16 | +
|
| 17 | +Input: nums = [4,5,6,7,0,1,2], target = 3 |
| 18 | +Output: -1 |
| 19 | +
|
| 20 | +
|
| 21 | +
|
| 22 | +
|
| 23 | +
|
| 24 | +
|
| 25 | +
|
| 26 | +
|
| 27 | +class Solution { |
| 28 | +public: |
| 29 | +
|
| 30 | + int pivot(vector<int>&nums){ |
| 31 | + int l=0, r=nums.size()-1, mid, n=nums.size(); |
| 32 | + while(l<=r){ |
| 33 | + mid=l+(r-l)/2; |
| 34 | + int prev=(mid-1+n)%n; |
| 35 | + int next=(mid+1)%n; |
| 36 | + if(nums[mid]<nums[prev] && nums[mid]<nums[next]) |
| 37 | + return mid; |
| 38 | + else if(nums[mid]<nums[r]) r=mid-1; |
| 39 | + else l=mid+1; |
| 40 | + } |
| 41 | + return -1; |
| 42 | + } |
| 43 | +
|
| 44 | + int bSearch(vector<int> &nums, int l, int r, int target){ |
| 45 | + int mid; |
| 46 | + while(l<=r){ |
| 47 | + mid=l+(r-l)/2; |
| 48 | + if(nums[mid]==target) return mid; |
| 49 | + else if(nums[mid]<target) l=mid+1; |
| 50 | + else r=mid-1; |
| 51 | + } |
| 52 | + return -1; |
| 53 | + } |
| 54 | +
|
| 55 | +
|
| 56 | + int search(vector<int>& nums, int target) { |
| 57 | + int n=nums.size(); |
| 58 | + if(n<=0) return -1; |
| 59 | + if(n==1){ |
| 60 | + if(nums[0]==target) return 0; |
| 61 | + else return -1; |
| 62 | + } |
| 63 | +
|
| 64 | + int piv=pivot(nums); |
| 65 | + int left=bSearch(nums,0, piv-1, target); |
| 66 | + int right=bSearch(nums,piv, n-1, target); |
| 67 | + if(left>=0) return left; |
| 68 | + else if(right>=0) return right; |
| 69 | + else return -1; |
| 70 | + } |
| 71 | +}; |
0 commit comments