1. 程式人生 > >Find Minimum in Rotated Sorted Array II:帶重複的陣列中找到升序數列的轉折點

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 an array sorted in ascending order 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.


思路:二分查詢,只不過因為有重複元素,所以對於這種情況:

[10,1,10,10,10]與[10,10,10,1,10]情況,僅從邊界與中值的大小無法判斷兩種情況的轉折點在哪,所以若相等則移動邊界。最壞複雜度為O(n)而不是logN。

[10,1,10,10,10]->[1,10,10,10]->二分查詢

[10,10,10,1,10]->[10,10,1,10]->[10,1,10]->二分查詢

class Solution {
    public int findMin(int[] nums) {
        if(nums.length==0) return 0;  
        int start =0;
        int end = nums.length-1;
        while(start<end){
            if(nums[start]<nums[end]){
                return nums[start];
            }
            int mid = (start + end)/2;
            if(nums[start]<nums[mid]){
                start = mid + 1;
            }else if(nums[start]>nums[mid]){
                end = mid;
            }else{// 如[10,1,10,10,10]與[10,10,10,1,10]情況,僅從邊界與中值的大小無法判斷兩種情況的轉折點在哪,所以若相等則移動邊界
                start++;
            }   
        }
        return nums[start];  
    }
}