Leetcode 81. Search in Rotated Sorted Array II
You are given an integer array nums
sorted in ascending order (with distinct values) that has been rotated at an unknown pivot index. You are also given an integer target
. Suppose the array initially looked like this: [0,1,2,4,5,6,7]
and it was rotated at an unknown pivot index [4,5,6,7,0,1,2]
.
Write a function to search target
in nums
. If target
exists, then return its index. Otherwise, return -1
.
left
and right
at the start and end of the array.left
<= right
, calculate mid
.nums[mid]
is the target.nums[left]
is equal to nums[mid]
, move the left
pointer right by one (left++
) to skip the duplicate.nums[mid]
is equal to nums[right]
, move the right
pointer left by one (right--
) to skip the duplicate.left
or right
to narrow the search.public class Solution {
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) return -1;
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
// the only change is here: handling duplicates
if (nums[left] == nums[mid] && nums[mid] == nums[right]) {
++left;
--right;
} else if (nums[left] <= nums[mid]) { // left part is sorted
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else { // right part is sorted
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1; // target not found
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {4,5,6,7,0,1,2};
int target = 0;
System.out.println(sol.search(nums, target)); // Output: 4
}
}
left
or right
, effectively searching the array linearly.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?