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.
You may assume no duplicate exists in the array.
题目大意:给定一个有序数组,是经过旋转过的,不知道在哪儿旋转的,求数组最小元素。
解题思路:直接遍历可以,太low。二分搜索吧,有序数组旋转有个特征,旋转后面的元素比旋转点前面的所有元素都小。
Talk is cheap>>
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int low = 0;
int high = nums.length - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) >> 1;
int left = mid > 0 ? mid - 1 : 0;
int right = mid < nums.length - 1 ? mid + 1 : nums.length - 1;
if (nums[mid] <= nums[left] && nums[mid] <= nums[right]) {
break;
}
if (nums[mid] >= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return nums[mid];
}