首页 > 代码库 > LeetCode Find Minimum in Rotated Sorted Array II

LeetCode 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.

Show Tags
Have you met this question in a real interview? 
Yes
 
No

Discuss

题意:求一个由不降序的数组转换成的新数组的最小值是多少

思路:第一种方法是:我们可以画出一个不降序的线段,然后有可能在任意点切掉,这个就是断点,所以可以看出出现第一个s[i]<s[i-1]的数的话,那么第i个数就是满足的

class Solution {
public:
    int findMin(vector<int> &num) {
        if (num.size() == 0)
            return 0;
        if (num.size() == 1)
            return num[0];
            
        for (int i = 1; i < num.size(); i++)
            if (num[i] < num[i-1])
                return num[i];
        return num[0];
    }
};
第二种方法是:用vector自带的min_element暴力出来

class Solution {
public:
    int findMin(vector<int> &num) {
        if (num.size() == 0)
            return 0;
            
        vector<int>::iterator it = min_element(num.begin(), num.end());
        return *it;
    }
};

第三种方法是:二分,这个比较需要考虑了,我是按照第一种方法的思路,尝试的画断点,还要注意的是要考虑:出现重复数的时候,我们通过left=left+1来缩小范围,我本来的想法是画图分析后是结果靠左边的,但是又错又超时。

class Solution {
public:
    int findMin(vector<int> &num) {
        int left = 0;
        int right = num.size() - 1;
        while (left < right) {
            if (num[left] < num[right])
                break;
            int mid = (left + right) / 2;
            if (num[mid] > num[right])
                left = mid + 1;
            else if (num[left] > num[mid])
                right = mid;
            else 
                left = left + 1;
        }
        return num[left];
    }
};


LeetCode Find Minimum in Rotated Sorted Array II