
题目:
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.
说明:
1)和1比只是有重复的数字,整体仍采用二分查找
2)方法二 :
实现:
一、我的实现:
class Solution {
public:
bool search(int A[], int n, int target) {
if(n==||n==&&A[]!=target) return false;
if(A[]==target) return true;
int i=;
while(A[i-]<=A[i]) i++; bool pre=binary_search(A,,i,target);
bool pos=binary_search(A,i,n-i,target);
return pre==false?pos:pre;
}
private:
bool binary_search(int *B,int lo,int len,int goal)
{
int low=lo;
int high=lo+len-;
while(low<=high)
{
int middle=(low+high)/;
if(goal==B[middle])//找到,返回index
return true;
else if(B[middle]<goal)//在右边
low=middle+;
else//在左边
high=middle-;
}
return false;//没有,返回-1
}
};
二、网上开源实现:
class Solution {
public:
bool search(int A[], int n, int target) {
int low=;
int high=n-;
while(low<=high)
{
const int middle=(low+high)/;
if(A[middle]==target) return true;
if(A[low]<A[middle])
{
if(A[low]<=target&&target<A[middle])
high=middle-;
else
low=middle+;
}
else if(A[low]>A[middle])
{
if(A[middle]<target&&target<=A[high])
low=middle+;
else
high=middle-;
}
else
low++;
}
return false;
}
};