LeetCode Solutions
81. Search in Rotated Sorted Array II
Time: $O(\log n) \to O(n)$ Space: $O(1)$
class Solution {
public:
bool search(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() - 1;
while (l <= r) {
const int m = (l + r) / 2;
if (nums[m] == target)
return true;
if (nums[l] == nums[m] && nums[m] == nums[r]) {
++l;
--r;
} else if (nums[l] <= nums[m]) { // nums[l..m] are sorted
if (nums[l] <= target && target < nums[m])
r = m - 1;
else
l = m + 1;
} else { // nums[m..n - 1] are sorted
if (nums[m] < target && target <= nums[r])
l = m + 1;
else
r = m - 1;
}
}
return false;
}
};
class Solution {
public boolean search(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
while (l <= r) {
final int m = (l + r) / 2;
if (nums[m] == target)
return true;
if (nums[l] == nums[m] && nums[m] == nums[r]) {
++l;
--r;
} else if (nums[l] <= nums[m]) { // nums[l..m] are sorted
if (nums[l] <= target && target < nums[m])
r = m - 1;
else
l = m + 1;
} else { // nums[m..n - 1] are sorted
if (nums[m] < target && target <= nums[r])
l = m + 1;
else
r = m - 1;
}
}
return false;
}
}
class Solution:
def search(self, nums: List[int], target: int) -> bool:
l = 0
r = len(nums) - 1
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return True
if nums[l] == nums[m] == nums[r]:
l += 1
r -= 1
elif nums[l] <= nums[m]: # nums[l..m] are sorted
if nums[l] <= target < nums[m]:
r = m - 1
else:
l = m + 1
else: # nums[m..n - 1] are sorted
if nums[m] < target <= nums[r]:
l = m + 1
else:
r = m - 1
return False