leetcode 154: Find Minimum in Rotated Sorted Array II

Find Minimum in Rotated Sorted Array II

Total Accepted: 12842 Total Submissions: 42907

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.

[分析]

在I的基础上, 稍作修改. 如果 mid值 == low or high值, 那么就 ++ or -- .

worst time complicity is O(n^2)

[注意事项]
NONE

[CODE]

public class Solution { 
    public int findMin(int[] num) { 
        if(num==null || num.length < 1) return 0; // ask interviewer which value should return: Integer.MIN_VALUE or throw a Exception. 
         
        int low = 0, high = num.length-1; 
        while(low < high) { 
            int mid = low + (high-low)/2;    
            int x = num[mid];  
             
            if(num[low] < num[high]) return num[low]; 
             
            if(num[mid] < num[low]) { 
                high = mid; 
            } else if(num[mid] > num[low]) { 
                low = mid; 
            } else { 
                ++low; 
            } 
        } 
        return num[low]; 
    } 
}


你可能感兴趣的:(leetcode 154: Find Minimum in Rotated Sorted Array II)