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;
}
};
本文介绍了一种在含有重复元素的旋转有序数组中查找特定目标值的方法。通过改进二分查找算法,文章提供了一种有效解决方案,并详细解释了其运行时复杂度的影响因素。

被折叠的 条评论
为什么被折叠?



