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());
    }
};

二分搜索最小值

if the array is indeed rotated by some pivot, there are only 2 possibilities

a[mid] > a[left] && a[mid] > a[right], meaning we are on the bigger part, the smaller part is on our right, so go right
a[mid] < a[left] && a[mid] < a[right], meaning we are on the smaller part, to find the smallest element, go left

if the array is not rotated (actually one rotating cycle completed), we just need to go left, in this case a[mid] < a[right] always holds.

combining the cases above, we conclude that

if a[mid] > a[right], go right; if a[mid] < a[right], go left.
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)