2015年6月8日星期一

Find Minimum in Rotated Sorted Array II leetcode

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.
方法类似于Search in Rotated Sorted Array II 当mid与end相等
的情况下 把边界向左移动 同时mid也会相应的移动
exp[1,3,3] mid = 3 end = 3, end--后 end = 3 mid = 1 所以end = mid --> result是1
算法的时间复杂度变成O(n) 最坏可能O(n)

public class Solution {

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

没有评论:

发表评论