Find Minimum in Rotated Sorted Array II, Leetcode 解题笔记

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.

此题已经在上题中讨论过了,最坏复杂度变成了O(n)。

public class Solution {
    public int findMin(int[] num) {
        int left = 0;
        int right = num.length-1;
        int min = Integer.MAX_VALUE;
        while(left < right-1){
            int mid = (left + right)/2;
            if(num[mid] > num[left]){
                min = Math.min(min, num[left]);
                left = mid + 1;
            }
            else if(num[mid] < num[left]){
                min = Math.min(min, num[mid]);
                right = mid - 1;
            }
            else{
                left++;
            }
        }
        min = Math.min(Math.min(min, num[left]), num[right]);
        return min;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s