LeetCode(154) Find Minimum in Rotated Sorted Array II

来源:互联网 发布:域名icp备案 编辑:程序博客网 时间:2024/04/27 16:51

题目如下:

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,用变形的二分查找即可。实际上有些细节不太好想。

1 如果mid和两端相等,该舍弃哪一半?答案是,不能一次舍弃一半,只能逐个元素舍弃,在这样的情况下,最坏时间复杂度为O(N)。官网解答是这么写的:

For case where AL == AM == AR, the minimum could be on AM’s left or right side (eg, [1, 1, 1, 0, 1] or [1, 0, 1, 1, 1]). In this case, we could not discard either subarrays and therefore such worst case degenerates to the order of O(n).

2 while(start < end)这个条件这样写正确吗?

我看到网上几个答案的写法是while (start < end - 1),我觉得这个写法比较不好理解,也不和上题 Find Minimum in Rotated Sorted Array I  一致。 所以改为了while (start < end)这样的写法,是可以通过测试的。


我的代码:

修改了左耳朵耗子 的解法。

//derived from haoel //12msclass Solution {public:int findMin(vector<int> &num) {    int start = 0, end = num.size() - 1, mid = 0;    while (start < end) {         while (start < end && num[start] == num[end]) //滤重,本题最重要的地方!            ++start;         mid  = start + (end - start)/2;        if (num[start] <= num[mid] && num[mid] <= num[end]) //如果是正常的升序数组            return num[start];        if (num[start] > num[mid]) { //和Find Minimum in Rotated Sorted Array I类似的逻辑            end = mid;        } else if (num[mid] > num[end]) { //和Find Minimum in Rotated Sorted Array I类似的逻辑            start = mid + 1;        }    }    return num[start] < num[end] ? num[start] : num[end]; //化简到最后,可能是1个元素或者2个元素。    }};


参考资料:

1 https://github.com/haoel/leetcode/blob/master/src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.II.cpp



0 0
原创粉丝点击