Suppose an array sorted in ascending order 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.
思路:153的followup,数组中可能存在重复元素,极端情况是11111011,这种情况下得到middle后,无法判断最小值在middle左侧还是右侧,最保险的做法是right左移一步,期待下次二分法能缩小范围。
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0, right = nums.length - 1;
while (left + 1 < right) {
int middile = left + (right - left) / 2;
if (nums[middile] > nums[right]) {
left = middile;
} else if (nums[middile] < nums[right]) {
right = middile;
} else {
right--;
}
}
return Math.min(nums[left], nums[right]);
}