153. Find Minimum in Rotated Sorted Array

Suppose a sorted array 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.

STL库函数

class Solution {
public:
    int findMin(vector<int>& nums) {
        return *min_element(nums.begin(), nums.end());
    }
};

二分搜索最小值

class Solution {
public:
    int findMin(vector<int>& nums) {
        int l = 0, r = nums.size() - 1;
        int last = r;
        //4 5 6 7 0 1 2
        //0 1 2 4 5 6 7
        while(l <= r){
            int mid = (l + r) / 2;
            //在左边
            if(nums[mid] > nums[last]) l = mid + 1;
            else r = mid - 1;
        }
        return nums[l];
    }
};

你可能感兴趣的:(153. Find Minimum in Rotated Sorted Array)