Example: Search in rotated sorted array II
class Solution {
public boolean search(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = (left+right)/2;
if(target==nums[mid]) return true;
if(nums[left]==nums[mid] && nums[mid] == nums[right]){
left++;
right--;
continue;
}
if(nums[left]<=nums[mid]){
if(target<nums[mid] && target>=nums[left]) right = mid-1;
else left= mid+1;
}
else {
if(target > nums[mid] && target<= nums[right]) left = mid+1;
else right = mid-1;
}
}
return false;
}
}
Top comments (1)
That modified binary search that handles duplicates by adjusting
leftandrightis a clever trick. I'm curious about its performance when the array has lots of duplicates. Does it end up with linear time complexity? I usually use LeetCode for these problems, but PracHub has a dedicated section for company-specific variations of binary search problems. It might be worth checking out for practice.