题目描述
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.
/** 旋转数组中寻找target,主要考虑左、右边界与中间元素相等
3 1 2 3 3 3 3
3 3 3 3 1 2 3 这种情况无法排除掉保留那一半数据,只能去掉首尾元素缩进,退化到O(n)复杂度
**/
class Solution {
public:
bool search(int A[], int n, int target)
{
int low = 0,high = n-1;
while(low<=high)
{
int middle = (low+high)>>1;
if(A[middle] == target)
return true;
if(A[middle]==A[high] && A[middle]==A[low]) /// 比unique查找多了两句
{
low++;
high--;
}
else if(A[low] <= A[middle]) /// left side is sorted
{
if(A[low]<=target && target<A[middle])
high = middle-1;
else
low = middle+1;
}
else /// right side id sorted
{
if(A[middle]<target && target<=A[high])
low = middle+1;
else
high = middle-1;
}
}
return false;
}
};