Search in Rotated Sorted Array II
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.
解题方法:
类似上面一题,同样是旋转数组的值查找问题。不过该数组包含重复数值。当A[low]==A[mid]时候不能确定low到mid之间数组的递增、递减情况。得按照特殊情况重新处理考虑。
Code:
bool Search(int A[],int n,int target){
int low=0,high=n;
while(low!=high){
const int mid=(low+high)/2;
if(A[mid]==target)
return true;
if(A[low]<A[mid]){
if(A[low]<=target && target<A[mid])
high=mid;
else
low=mid+1;
}else if(A[first]>A[mid]){
if(A[mid]<target &&target<=A[high-1])
low=mid+1;
else
high=mid;
}else
low++;
}
return false;
}