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.
Subscribe to see which companies asked this question
1 public class Solution { 2 public int findMin(int[] nums) { 3 if(nums == null) return 0; 4 int low = 0,high = nums.length-1; 5 if(nums[low] <= nums[high]) return nums[0]; 6 int mid = 0; 7 while(low < high){ 8 mid = (low + high)/2; 9 if(nums[mid] > nums[mid+1]) return nums[mid+1];// 后面的数字比前面小,就可以找到了。 10 if(nums[mid] > nums[low]) low = mid; 11 else high = mid; 12 } 13 return nums[0]; 14 } 15 }
这里用二分做的时候,经常分不清楚情况。