Suppose a sorted array is rotated on some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You is given a target value to search. If found in the array is return its index, otherwise return-1.
Assume no duplicate exists in the array.
Analysis: Using two-point search method. Mid = (low + high)/2. Consider two scenarios such as:
1. If Nums[low] <= Nums[mid] indicates that the interval is incremented, if the value of target is between the two, then the upper bound is mid-1, otherwise the lower bound is mid + 1;
2. If Nums[low] > Nums[mid] indicates that mid is after the maximum value (example: [4, 5, 6, 0, 1, 2, 3]. Number 0 after 6) If Target is between Nums[mid] and Nums[high], the lower bound is mid + 1; otherwise the upper bound is mid-1.
Run Time 7ms
1 classSolution {2 Public:3 intSearch (vector<int>& Nums,inttarget) {4 if(nums.size () = =0)return-1;5 if(nums.size () = =1){6 if(nums[0] = = target)return 0;7 Else return-1;8 }9 Ten intLow =0, high = Nums.size ()-1; One while(Low <=High ) { A intMid = (low + high)/2; - if(Nums[mid] = = target)returnmid; - if(Nums[low] <=Nums[mid]) { the if(Nums[low] <= target && target < Nums[mid]) high =mid; - ElseLow = mid +1; - } - Else{ + if(Nums[mid] < target && target <= nums[high]) Low = mid +1; - ElseHigh =mid; + } A } at return-1; - } -};
Search in rotated Sorted Array