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.
解答:
考虑几个例子
4 5 6 7 0 1 2
2 4 5 6 7 0 1
5 6 7 0 1 2 4
6 7 0 1 2 4 5
可以发现,中间的数假如大于最右边的数,那么左边的数都是单调递增的,否则右边的数都是单调递增的。那么可以考虑单调递增的区间的最左边和最右边与target的大小·,这样就能判断出target在不在这个区间,不在的话就在另一个区间中。
class Solution {
public:
int search(vector<int>& nums, int target) {
int n=nums.size()-1;
int left=0,right=n;
while(left<=right)
{
int mid=(left+right)/2;
if(nums[mid]==target) return mid;
if(nums[mid]<nums[right])
{
if(nums[right]>=target&&nums[mid]<target) left=mid+1;
else right=mid-1;
}
else
{
if(nums[left]<=target&&nums[mid]>target) right=mid-1;
else left=mid+1;
}
}
return -1;
}
};