xinyu04

导航

LeetCode 153 Find Minimum in Rotated Sorted Array 二分

Suppose an array of length \(n\) sorted in ascending order is rotated between \(1\) and \(n\) times. For example, the array nums = [0,1,2,4,5,6,7] might become:

  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • [0,1,2,4,5,6,7] if it was rotated 7 times.

Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in \(O(\log n)\) time.

Solution

和之前的问题很相似,但是这次需要找到最小值。还是利用二分,当 \(nums[l]<nums[r]\) 时,就意味着这段区间是有序的;否则我们继续进行二分即可

点击查看代码
class Solution {
public:
    int findMin(vector<int>& nums) {
        int n = nums.size();
        int l = 0, r = n-1;
        if(n==2) return min(nums[0], nums[1]);
        while(l<r){
            int mid = l+(r-l)/2;
            if(nums[l]<nums[r] && nums[l]<=nums[0])return nums[l];

            if(nums[l]<=nums[mid]) l = mid+1;
            else r = mid;
        }
        return nums[r];
    }
};

posted on 2022-07-29 17:05  Blackzxy  阅读(8)  评论(0编辑  收藏  举报