Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/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题目类似,只是允许了重复元素。Find Minimum in Rotated Sorted Array这题还是一个多月前做的了,有点忘记了思路。所以这次重写了一遍,以前的思路果然是幼稚啊...

这个系列的题目和前面做的Search in Rotated Sorted Array II系列非常像,处理重复元素的思路也非常像。

元素重复会有什么影响?考虑例子,4 0 222222,num[mid] == num[end]的时候,不不能直接返回了。真正返回的条件是它们的下标相等。当num[mid] == num[end]的时候,将end--即可。这个思路在Search in Rotated Sorted Array II里也是这么解决的。

public class Solution {
    public int findMin(int[] num) {
        int start = 0;
        int end = num.length - 1;
        while(start <= end){
            int mid = (start + end) / 2;
            if(mid == end){
                return num[mid];
            }
            if(num[end] == num[mid]){
                end--;
            }
            if(num[end] < num[mid]){
                start = mid + 1;
            }
            if(num[end] > num[mid]){
                end = mid;
            }
        }
        return -1;
    }
}

元素允许重复后,最差情况,比如4 0 2 2 2 2 2 2 2 2 2 2 2 2 2,num[mid]和num[end]不断相等,end不断需要--。所以可能要花到O(n)的时间。

posted on 2015-03-11 14:53  NickyYe  阅读(229)  评论(0编辑  收藏  举报