Leetcode 81. Search in Rotated Sorted Array II
Suppose an array sorted in non-decreasing order is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
). You are given a target value to search. If found in the array return true
, otherwise return false
.
This array may contain duplicates.
You must decrease the overall time complexity.
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
nums
is guaranteed to be rotated at some pivot.-10^4 <= target <= 10^4
mid
.nums[mid]
== target, return true.start
, mid
, and end
are equal, shrink the search range by moving the start and end pointers inward.nums[start]
to nums[mid]
is sorted, determine if the target is in this range.nums[mid]
to nums[end]
is sorted, determine if the target is in this range.#include <vector>
using namespace std;
class Solution {
public:
bool search(vector<int>& nums, int target) {
int start = 0, end = nums.size() - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return true;
}
// Handle duplicates by narrowing the range.
if (nums[start] == nums[mid] && nums[mid] == nums[end]) {
start++;
end--;
}
// Left part is sorted.
else if (nums[start] <= nums[mid]) {
// Target is in the sorted left part.
if (nums[start] <= target && target < nums[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
// Right part is sorted.
else {
// Target is in the sorted right part.
if (nums[mid] < target && target <= nums[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return false;
}
};
The worst-case time complexity of this approach is O(n) because in the case of many duplicates, we might end up checking every element. However, in the average case, it should perform better, typically closer to O(log n) when there are fewer duplicates.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?