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.
代码
class Solution {
public:
bool search(vector<int>& nums, int target) {
int low=0,high=nums.size()-1,middle;
while(low<=high){
middle=(low+high)/2;
if(target == nums[middle]){ //先确定middle值是不是target
return true;
}
if(nums[low]==nums[middle]){ //当low和middle位置值相等时(low去掉,middle保留,所以无影响)
low++;
}else if(nums[low]<nums[middle]){ //左边有序
if(nums[low]<=target && target<nums[middle]){ //target在middle左边区域
high=middle-1;
}else{
low=middle+1;
}
}else{ //右边有序
if(nums[middle]<target && target<=nums[high]){ //target在目标右边区域
low=middle+1;
}else{
high=middle-1;
}
}
}
return false;
}
};