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.
Example 1:
Input: [3,4,5,1,2] Output: 1
Example 2:
Input: [4,5,6,7,0,1,2] Output: 0
binary search
旋转后的数组由两个递增的部分组成,max在min的左边,左半部分的元素比右半部分大。
先判断l,r所对应元素的大小关系,如果nums[l] < nums[r]说明数组是有序的,没有旋转,直接返回nums[l]就行。
然后找中点,判断nums[mid]和nums[r]的大小关系,如果nums[mid] < nums[r],说明从mid到r这半部分是有序的,最小值应该在左半部分;反之应该在右半部分。最后返回nums[l]
时间:O(logN),空间:O(1)
class Solution { public int findMin(int[] nums) { int l = 0, r = nums.length - 1; if(nums[l] < nums[r]) return nums[l]; // no rotation while(l < r) { int mid = l + (r - l) / 2; if(nums[mid] < nums[r]) r = mid; else l = mid + 1; } return nums[l]; } }