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.
我们来观察一下:
01234
12340
23401
34012
40123
如果中间的值大于左边和右边的,那我们要找的在右边
如果中间值小于左边的和右边的,那我们要找的在左边
如果中间值大于左边小于右边的,那左边的就是我们要找的
var findMin = function(nums) {
var left = 0;
var right = nums.length - 1;
while (left<right) {
var mid = left + parseInt((right - left) / 2);
if (nums[mid]>=nums[left]&&nums[mid]>=nums[right])
left = mid + 1;
else if (nums[mid]<=nums[left]&&nums[mid]<=nums[right])
right = mid;
else if (nums[mid]>=nums[left]&&nums[mid]<=nums[right])
return nums[left];
}
return nums[left];
};