Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
这道题和第33题类似,但是这道题允许重复元素出现,则上一道题中的nums[l] <= nums[mid] 条件就不能确定左半部分[l mid]区间为递增有序序列了。
比如:{1,3,1,1,1,1}
如果nums[l] <= nums[mid] 条件就不能确定[l mid]区间为递增有序序列,我们就把该条件分成两个字条件:
nums[l] < nums[mid] 则 [l mid]区间为递增有序序列
nums[l] = nums[mid] 则[l mid]区间不能确定,那就l++,往下一步看看即可。
class Solution {
public:
bool search(vector<int>& nums, int target)
{
int l=0;
int r=nums.size()-1;
while(l<=r)
{
int mid=(l+r)/2;
if(target==nums[mid])
return true;
else if(nums[l]<nums[mid])//左半部分有序
{
if(target>=nums[l]&&target<nums[mid])
r=mid-1;
else
l=mid+1;
}
else if(nums[l]>nums[mid])//右半部分有序
{
if(target>nums[mid]&&target<=nums[r])
l=mid+1;
else
r=mid-1;
}
else
l++;
}
return false;
}
};