原题:
解决方法:
Suppose an array sorted in ascending order is rotated at 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 are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
二分查找的变形题。根据中点与起点的位置得到中点是在第一递增区间还是第二递增区间,然后很容易得出是继续在递增区间查找还是在混合区间去查找。
int search(vector<int>& nums, int target) {
int lo = 0, hi = nums.size() -1;
while(lo <= hi){
int mid = lo + ( (hi - lo) >> 1);
if (nums[mid] == target)
return mid;
if (nums[mid] >= nums[lo]){
if (nums[lo] <= target && target < nums[mid]){
hi = mid - 1;
}else{
lo = mid + 1;
}
}else{
if ( nums[hi] >= target && nums[mid] < target ){
lo = mid + 1;
}else{
hi = mid - 1;
}
}
}
return lo < nums.size() ? ( nums[lo] == target ? lo : -1 ) : -1;
}