Search in Rotated Sorted Array II
Q: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:有重复的元素。
bool bisearch(int A[],int begin,int end,int target)
{
if(begin>end)
return false;
int middle = begin+(end-begin)/2;
if(A[middle] == target)
return true;
if(A[begin]>=A[end]) //--这里不一样
{
return bisearch(A,begin,middle-1,target)||bisearch(A,middle+1,end,target);
}else
{
if(A[middle]>target)
return bisearch(A,begin,middle-1,target);
else
return bisearch(A,middle+1,end,target);
}
}
bool search(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return bisearch(A,0,n-1,target);
}
浙公网安备 33010602011771号