https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/
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.
You may assume no duplicate exists in the array.
注意,我们要找的最小值,只会在右端,所以如果已经在右端,则挪RIGHT
如果在左端,则挪LEFT 往右端的深沟走
time: o(logn) space: o(1)
1 public int findMin(int[] nums) { 2 if (nums ==null || nums.length ==0) return -1 ; 3 int left = 0, right = nums.length -1 ; 4 while(left + 1 < right){ 5 int mid = left +(right-left)/2 ; 6 //lower part 7 if (nums[mid]<nums[right]){ 8 right = mid ; 9 } 10 //upper part: 这里没有 duplicate, 所以写 nums[mid] > nums[left] 一样通过 11 else if(nums[mid]>nums[right]){ 12 left = mid ; 13 } 14 } 15 //post processing 16 return Math.min(nums[left], nums[right]) ; 17 }
这个笨方法也能通过
1 public int findMin(int[] nums) { 2 if (nums ==null || nums.length ==0) return -1 ; 3 int left = 0, right = nums.length -1 ; 4 while(left + 1 < right){ 5 int mid = left +(right-left)/2 ; 6 //this is the case for test case [1,2,3]: not necessary rotated 7 if(nums[left] <= nums[mid] && nums[mid]<=nums[right]){ 8 right = mid ; 9 } 10 else if (nums[mid] > nums[left] && nums[mid]>=nums[right]){ 11 left = mid ; 12 } else if(nums[mid]<=nums[left]){ 13 right = mid ; 14 } 15 } 16 //post processing 17 return Math.min(nums[left], nums[right]) ; 18 }