leetcode153 - Find Minimum in Rotated Sorted Array - medium

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
 
min就是右下那块的起点,刚好用另一种模板,m = l+r >> 1取floor, 右半边返回true,移动时r = m,l = m+1. 
这里绿色区域的条件很简单,就是nums[m] <= nums[r]
当然如果nums[l]已经小于nums[r]的话可以直接返回nums[l]
leetcode153 - Find Minimum in Rotated Sorted Array - medium_第1张图片
 
实现:
class Solution {
public:
    int findMin(vector<int>& nums) {
        
        if (nums.empty())
            return -1;
        
        int l = 0, r = nums.size()-1;
        while (l < r){
            int m = l + (r-l)/2;
            if (nums[m] <= nums[r])
                r = m;
            else
                l = m + 1;
        }
        
        return nums[r];
        
    }
};

 

你可能感兴趣的:(leetcode153 - Find Minimum in Rotated Sorted Array - medium)