Search in Rotated Sorted Array II
题目:
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,就一个是2,然后找2,二分法的特性就被破坏了,所以worst case变成linear的了。
解法:
class Solution {
/**
* param A : an integer ratated sorted array and duplicates are allowed
* param target : an integer to be search
* return : a boolean
*/
public:
bool search(vector<int> &A, int target) {
// write your code here
if (A.size() == 0) {
return false;
}
int start = 0;
int end = A.size() - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) {
return true;
}
if (A[start] == A[end] || A[mid] == A[end]) {
end--;
continue;
}
if (A[mid] < A[end]) {
if (A[mid] < target && target <= A[end]) {
start = mid;
} else {
end = mid;
}
} else {
if (target < A[mid] && A[start] <= target) {
end = mid;
} else {
start = mid;
}
}
}
if (A[start] == target || A[end] == target) {
return true;
}
return false;
}
};