154. Find Minimum in Rotated Sorted Array II

时间:2023-01-15 04:27:45

问题描述:

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.

The array may contain duplicates.

Example 1:

Input: [1,3,5]
Output: 1

Example 2:

Input: [2,2,2,0,1]
Output: 0

Note:

解题思路:

这道题的不同之处在于可能会出现重复的数字。

我们通过判断nums[mid] 与两端的关系来判断轴可能出现的地方:

  1. nums[mid] > nums[r] : 轴在 (mid, r] 之间

  2. nums[mid] < nums[r] : 轴在[l, mid]之间

若nums[mid] == nums[r] 则我们需要将r向左移动至一个不等于且不小于mid的位置

也就是说边界位置为r = mid

空间复杂度O(1), 时间复杂度O(logn),若极端情况:全部相等时,为O(n)

代码:

class Solution {
public:
    int findMin(vector<int>& nums) {
        int l = 0, r = nums.size()-1;
        while(l < r){
            int mid = l + (r - l)/2;
            while(r > mid && nums[mid] == nums[r]) r--;
            if(r < mid) continue;
            if(nums[mid] > nums[r]) l = mid+1;
            else r = mid;
        }
        return nums[l];
    }
};