Find Minimum in Rotated Sorted Array II
Suppose a sorted array 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).
Find the minimum element. The array may contain duplicates.
Example:
Given [4,4,5,6,7,0,1,2] return 0.
Solution:
If we found duplicate, we need to move start or end. In ideal case, we should set start = mid or end = mid. However, since the array is rotated, the duplicate numbers could be appeared in both side of the array, for exemple: [4,4,5,6,7,0,1,2,4,4]. Therefore, we can only move start or end by one step at a time. For instance: if nums[mid] == nums[start], start++. If nums[mid] == nums[end], end--.
Code:
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return Integer.MAX_VALUE;
}
int start = 0;
int end = nums.length - 1;
int target = nums[end];
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[start] == nums[mid]) {
start++;
} else if (nums[end] == nums[mid]) {
end--;
} else if (nums[mid] <= target) {
end = mid;
} else {
start = mid;
}
}
if (nums[start] < nums[end]) {
return nums[start];
} else {
return nums[end];
}
}