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
如果右边[m, r]是递增的话,那么最小值可能在中间或者左侧:5 6 7 0 1 2 3或者7 0 1 2 3 5 6
左边[l, m]连续的话,最小值肯定在右侧
class Solution { public: int findMin(vector<int>& nums) { int len = nums.size(); int l, m, r, minV = INT_MAX; l = 0; r = len - 1; while(l <= r){ int m = (l + r) / 2; if(l == r){ minV = min(minV, nums[l]); break; } else if(nums[m] < nums[r]){ minV = min(minV, nums[m]); r = m - 1; } else l = m + 1; } return minV; } };