题目要求: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.
尝试直接寻找,超出时间限制。需要复杂度O(logn)
思路:先找到最小值点。寻找最小值点也是用二分法。如果中间点比右边点大,则最小值在中间点到右边点之间,否则,反之。
找到最小值点后,假设整个容器向右边扩充,left点设置为最小值点,right点设置为最小值点+n
class Solution {
public:
int search(vector<int>& nums, int target) {
int n=nums.size();
if(n==1){
if(target==nums[0]) return 0;
else return -1;
}
int i;
int rot=0;
int right=n-1,left=0,mid=(right+left)/2;
while(left<right){
//mid=(right+left)/2;
if(nums[mid]>nums[right]){
left=mid+1;
}
else{
right=mid;
}
mid=(right+left)/2;
}
rot=mid;
cout<<rot<<endl;
left=rot;
right=rot+n-1;
while(left<=right){
//cout<<1<<endl;
mid=((right+left)/2)%n;
if(target==nums[mid]){
return mid;
}
else if(target<nums[mid]){
right=(right+left)/2-1;
}
else{
left=(right+left)/2+1;
}
}
return -1;
}
};
这里有很多值得注意的细节。比如,在升序排列中的寻找,left=mid+1,right=mid-1,循环条件是left<=right。+1,-1很重要,不然可能在left和right只差一个的时候无限循环。