LeetCode Problem
81. Search in Rotated Sorted Array II
Link to LeetCode
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).
For example, [0,1,2,4,4,4,5,6,6,7] might be left rotated by 5 indices and become [4,5,6,6,7,0,1,2,4,4].
Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.
You must decrease the overall operation steps as much as possible.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
We only need to add one more condition, which checks if the left-most element and the right-most element are equal. If they are we can simply drop one of them. In my solution below, I drop the left element whenever the left-most equals to the right-most.
public int findMin(int[] nums) {
int i=0;
int j=nums.length-1;
while(i<=j){
//handle cases like [3, 1, 3]
while(nums[i]==nums[j] && i!=j){
i++;
}
if(nums[i]<=nums[j]){
return nums[i];
}
int m=(i+j)/2;
if(nums[m]>=nums[i]){
i=m+1;
}else{
j=m;
}
}
return -1;
}