154.Find Minimum in Rotated Sorted Array II

Follow up for “Find Minimum in Rotated Sorted Array”: What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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.

The array may contain duplicates.

这是Find Minimum in Rotated Sorted Array系列的第二题,和这个系列的第一题的思路相近,就是寻找在rotate之后依然有序的部分,但是这次有可能会出现nums[mid]==nums[high]的情况,之前处理过Search in Rotated Sorted Array II问题,当出现这种情况时,应该对high的值-1,然后继续判断。

Find Minimum in Rotated Sorted Array I算法的平均时间复杂度为O(log n),而在Find Minimum in Rotated Sorted Array II中,由于有重复元素的存在,那么会对时间复杂度造成影响,在最坏的情况下,比如整个数组由同一个元素组成时,这个算法就不得不一直对high的值进行调整,所以最坏的情况下时间复杂度为O(n)

代码如下:

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

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017