Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
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).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
s思路:
1. bianary search。两件事:一是重复;一是rotate。搁一块,就看相互影响不?显然是要影响的。先看没有重复时,:
上图,虽然rotate,但是总可以通过比较找到不是rotate且sorted一半。而一旦重复后,经过rotate,如下图:
我们比较发现left==right==mid,此时,我们就不能比较得出那一边是sorted的,事实上,当rotate后成为[1,1,1,1,7,1,1,1],left==right==mid,我们也是不知道的。因此,不能使用bianary search,就只能o(n)的遍历了!
3. 做的过程中,发现上面判断left==right==mid,有一个巨大的bug:方法1就是只比较nums[mid]和nums[left]: if(nums[mid]>nums[left])说明左侧是递增;if(nums[mid]
//方法1:bianary search.
class Solution {
public:
bool search(vector<int>& nums, int target) {
//
int left=0,right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==target) return true;
if(nums[mid]>nums[left]){
if(target>=nums[left]&&target<nums[mid])
right=mid-1;
else
left=mid+1;
}else if(nums[mid]<nums[left]){//大bug: if(nums[mid]<nums[right]){
if(target>nums[mid]&&target<=nums[right])
left=mid+1;
else
right=mid-1;
}else
//right--;
left++;
}
return false;
}
};
//变形:做法完全一样。但是
class Solution {
public:
bool search(vector<int>& nums, int target) {
//
int left=0,right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==target) return true;
if(nums[mid]>nums[right]){
if(target>=nums[left]&&target<nums[mid])
right=mid-1;
else
left=mid+1;
}else if(nums[mid]<nums[right]){//大bug: if(nums[mid]<nums[right]){
if(target>nums[mid]&&target<=nums[right])
left=mid+1;
else
right=mid-1;
}else
right--;
}
return false;
}
};