Suppose a sorted array 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.
仍然是二分查找,和之前的找最小很类似,只不过这次上下界的移动是根据mid和target比较的结果来决定的,情况分析如下:
mid>high, 如果target大于mid或者小于等于high这时候可以确定target位于mid和high 之间,low=mid+1;
mid<high, 如果target大于mid同时小于等于high这时候可以确定target位于mid和high之间,low=mid+1;
代码如下:
class Solution {
public:
int search(vector<int>& nums, int target) {
int low=0,high=nums.size()-1;
while(low<high){
int mid=(low+high)/2;
if(nums[mid]>nums[high]){
if(target>nums[mid]||target<=nums[high])
low=mid+1;
else
high=mid;
}else{
if(target>nums[mid]&&target<=nums[high])
low=mid+1;
else
high=mid;
}
}
if(low==high&&target!=nums[low]) return -1;
return low;
}
};