154. Find Minimum in Rotated Sorted Array II

problem description

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:

This is a follow up problem to Find Minimum in Rotated Sorted Array. Would allow duplicates affect the run-time complexity? How and why?

algorithm thought

上一题的拓展版本,可以有重复数字,我们需要处理的也是重复数字。每次对于最左边的数字,如果和右边的数字重复,就将left++。之后的处理基本和上一题一样了

这里需要理解的是,如果数组有序,直接返回left,否组数组肯定是两段有序,mid肯定在两段中的一段。mid和left相比,如果mid >= left,left-mid这段就是有序的,最小值肯定不再中间,mid < left,mid-right这段是有序的,最小值肯定不再这段

code

class Solution {
public:
    int findMin(vector<int>& nums) {
        int left=0,right=nums.size()-1;
        while(left<right){
            while(left<right-1&&nums[left]==nums[right]){
                left++;
            }
            if(nums[left]<nums[right])
                return nums[left];

            int mid=left+(right-left)/2;
            if(mid==left||nums[mid]>=nums[left])
                left=mid+1;
            else
                right=mid;
        }
        return nums[left];
    }
};

algorithm analysis

上一题时间复杂度是O(lgn),这里加入了重复数组计算,如果所有数字都是重复的,那么处理重复数字的时间复杂度会达到O(n),所以这里时间复杂度是O(n)

Last updated