Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
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.
Analysis:
Since there are duplicates, A[m] could be equal to A[b] or A[e]. If A[m] == A[e], then A[e] could not be the target so e = e -1 to shrink the search range. Similarly, if A[m] == A[b], let b = b+1 to shrink the range.
class Solution {
public:
bool search(int A[], int n, int target) {
int b = 0;
int e = n - 1;
while(b <= e)
{
int m = (b + e) / 2;
if (A[m] == target)
return true;
else if (A[m] == A[e])
e = e - 1;
else if (A[m] == A[b])
b = b + 1;
else if (A[m] < A[e])
{
if (target > A[m] && target <= A[e])
b = m + 1;
else
e = m - 1;
}
else
{
if (target < A[m] && target >= A[b])
e = m - 1;
else
b = m + 1;
}
}
return false;
}
};
No comments:
Post a Comment