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
用二分法查找,需要始终将目标值(这里是最小值)套住,并不断收缩左边界或右边界。
左、中、右三个位置的值相比较,有以下几种情况:
左值 < 中值, 中值 < 右值 :没有旋转,最小值在最左边,可以收缩右边界
右
中
左
左值 > 中值, 中值 < 右值 :有旋转,最小值在左半边,可以收缩右边界
左
右
中
左值 < 中值, 中值 > 右值 :有旋转,最小值在右半边,可以收缩左边界
中
左
右
左值 > 中值, 中值 > 右值 :单调递减,不可能出现
左
中
右
分析前面三种可能的情况,会发现情况1、2是一类,情况3是另一类。
如果中值 < 右值,则最小值在左半边,可以收缩右边界。
如果中值 > 右值,则最小值在右半边,可以收缩左边界。
通过比较中值与右值,可以确定最小值的位置范围,从而决定边界收缩的方向。
而情况1与情况3都是左值 < 中值,但是最小值位置范围却不同,这说明,如果只比较左值与中值,不能确定最小值的位置范围。
所以我们需要通过比较中值与右值来确定最小值的位置范围,进而确定边界收缩的方向。
作者:armeria-program
链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/solution/er-fen-cha-zhao-wei-shi-yao-zuo-you-bu-dui-cheng-z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1 class Solution { 2 public: 3 int findMin(vector<int>& nums) { 4 int low = 0; 5 int high = nums.size() - 1; 6 while(low < high) { 7 int mid = low + (high - low ) / 2; 8 if(nums[mid] < nums[high]) { 9 high = mid; 10 } else { 11 low = mid + 1; 12 } 13 } 14 return nums[low]; 15 } 16 };
1 class Solution { 2 public: 3 int findMin(vector<int>& nums) { 4 int low = 0; 5 int high = nums.size() - 1; 6 while(low < high) { 7 int mid = low + (high - low ) / 2; 8 // 如果单调递增,如【1,2,3,4】 直接返回最小值。 9 if (nums[low] < nums[high]) return nums[low]; 10 11 if(nums[low] <= nums[mid]) { 12 low = mid + 1; 13 } else if(nums[mid] <= nums[high]) { 14 high = mid; 15 } 16 } 17 return nums[low]; 18 } 19 };