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.
题意:查询给定目标值是否在数组中,是search in rotated sorted array的扩展。
思路:因为是上一题的扩展,所以很正常的想到,上题的思路,在本题是否合适。结果发现不能强行的套上去。如:1,1,3,1,target=3,若是按照原来的解法,则应该是左边有序,然而不行;若是if条件判断中间等号,为右边有序,也显然不对。参考了Grandyang的博客才知道,只需在判断上加上判断中间值是否等于最右端值,若是,hi向左移动一个,直到不相等。这样就可以继续保持上题的解法了,具体代码如下:
class Solution {
public:
bool search(int A[], int n, int target)
{
if(n==) return false;
int lo=,hi=n-;
while(lo<=hi)
{
int mid=(lo+hi)/;
if(A[mid]==target)
return true;
else if(A[mid]<A[hi])
{
if(A[mid]<target&&A[hi]>=target)
lo=mid+;
else
hi=mid-;
}
else if(A[mid]>A[hi])
{
if(A[lo]<=target&&A[mid]>target)
hi=mid-;
else
lo=mid+;
}
else //重点理解
hi--;
}
return false;
}
};