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

 

寻找旋转有序重复数组的最小值是对之前问题的延伸(http://www.cnblogs.com/grandyang/p/4032934.html),当数组中存在大量的重复数字时,就会破坏二分查找法的机制,我们无法取得O(lgn)的时间复杂度,又将会回到简单粗暴的O(n),比如如下两种情况:

{2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 1, 2} 和 {2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2}, 我们发现,当第一个数字和最后一个数字,还有中间那个数字全部相等的时候,二分查找法就崩溃了,因为它无法判断到底该去左半边还是右半边。这种情况下,我们只能回到最原始的那种简单粗暴的方法,把整个数组从头到尾撸一遍,找出最小的那个。代码如下:

 

class Solution {
public:
    int findMin(vector<int> &num) {
        if (num.size() <= 0) return 0;
        if (num.size() == 1) return num[0];

        int left = 0, right = num.size() - 1;
        if (num[left] > num[right]) {
            while (left != (right - 1)) {
                int mid = (left + right) / 2;
                if (num[left] <= num[mid]) left = mid;
                else right = mid;
            }
            return min(num[left], num[right]);
        } else if (num[left] == num[right]) {
            int res = num[0];
            for (int i = 1; i < num.size(); ++i) {
                res = min(res, num[i]);
            }
            return res;
        }
        return num[0];
    }
};

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:(LeetCode)