- 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.
Example
Example 1:
Input:
[]
1
Output:
false
Example 2:
Input:
[3,4,4,5,7,0,1,2]
4
Output:
true
解法1: Binary Search。
代码如下:
class Solution {
public:
/**
* @param A: an integer ratated sorted array and duplicates are allowed
* @param target: An integer
* @return: a boolean
*/
bool search(vector<int> &A, int target) {
int n = A.size();
if (n == 0) return false;
int start = 0, end = n - 1;
if (A[start] == target) return true;
if (A[end] == target) return true;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) return true;
if (A[mid] > A[start] && target < A[start]) start = mid;
else if (A[mid] < A[start] && target > A[start]) end = mid;
else {
if (A[mid] > target) end = mid;
else start = mid;
}
}
if (A[start] == target || A[end] == target) return true;
return false;
}
};
解法2:
如果 nums[left] == nums[mid] == nums[right],无法根据它们的相对大小判断「断崖」到底在 mid 的左边还是右边。
所以不要出现 nums[left] == nums[mid] == nums[right] 的情况,即在计算 mid 之前收缩 left, right 边界,提前消除重复元素:
class Solution {
public:
bool search(vector<int>& nums, int target) {
int n = nums.size();
int start = 0, end = n - 1;
while (start + 1 < end) {
while (start + 1 < end && nums[start] == nums[start + 1]) start++;
while (start + 1 < end && nums[end] == nums[end - 1]) end--;
int mid = start + (end - start) / 2;
if (nums[start] <= nums[mid]) { // mid is in the left part
if (nums[start] <= target && target <= nums[mid]) {
end = mid;
} else {
start = mid;
}
} else { // mid is in the right part
if (nums[mid] <= target && target <= nums[end]) {
start = mid;
} else {
end = mid;
}
}
}
if (nums[start] == target) return true;
if (nums[end] == target) return true;
return false;
}
};