题目:
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 I,先确定哪边是连续的,然后通过连续的那部分去判断需要向左还是向右。唯一的区别在于,由于有duplicated元素存在,可能导致无法判断哪边是连续的。例如,A[] = {2, 2, 1, 2},这时A[lower_bound] == A[mid] == A[upper_bound],现有的判断哪边是连续的条件在这里会失效。这里的做法是,由于已经判断完A[mid] != target,因此无论上界还是下界都是没有用的字符,所以可以将当前区间shrink.
class Solution {
public:
bool search(int A[], int n, int target) {
int lower_bound = 0;
int upper_bound = n - 1;
while (lower_bound <= upper_bound) {
int mid = (lower_bound + upper_bound) / 2;
if (A[mid] == target) {
return true;
} else if (A[lower_bound] == A[mid] && A[upper_bound] == A[mid]) { //shrink
lower_bound++;
upper_bound--;
} else if (A[lower_bound] <= A[mid]) { //left part consistent
if (A[lower_bound] <= target && A[mid] > target) { //go left
upper_bound = mid - 1;
} else {
lower_bound = mid + 1;
}
} else { //right part consistent
if (A[upper_bound] >= target && A[mid] < target) {
lower_bound = mid + 1;
} else {
upper_bound = mid - 1;
}
}
}
return false;
}
};
总结:复杂度为O(logn).