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.
class Solution {
public:
bool search(int A[], int n, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int left = 0, right = n-1;
while(left <= right) {
int middle = left + (right-left)/2;
if(A[middle] == target) return true;
if(A[middle] == A[left]) {
int index = middle;
while(index >= left && A[middle] == A[index]) index--;
if(index < left) {
if(A[middle] == target) return true;
left = middle+1;continue;
}
if(target <= A[right] && target >= A[middle]) return bSearch(A,target,middle,right);
right = middle-1;
continue;
}
if(A[middle] < A[left]) {
if(target <= A[right] && target >= A[middle]) return bSearch(A,target,middle,right);
right = middle-1;
continue;
}
if(A[middle] > A[left]) {
if(target <= A[middle] && target >= A[left]) return bSearch(A,target,left,middle);
left = middle+1;
continue;
}
}
return false;
}
bool bSearch(int A[],int target, int left, int right) {
while(left <= right) {
int middle = left + (right-left)/2;
if(target == A[middle]) return true;
if(target < A[middle]) right = middle-1;
else left = middle+1;
}
return false;
}
};