lintcode160- Find Minimum in Rotated Sorted Array II- medium

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode160- Find Minimum in Rotated Sorted Array II- medium相关的知识,希望对你有一定的参考价值。

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.

 Notice

The array may contain duplicates.

Example

Given [4,4,5,6,7,0,1,2] return 0.

 

和I类似,OOXX二分法(find the first X),只是对比对象变掉。从原来的最后一个数,变为最后开始数起第一个比不等于nums[0]的数。

 

public class Solution {
    /*
     * @param nums: a rotated sorted array
     * @return: the minimum number in the array
     */
    public int findMin(int[] nums) {

        //返回int这里怎么处理?
        if (nums == null || nums.length == 0){
            throw new IllegalArgumentException();
        }

        int start = 0;
        int end = nums.length - 1;

        while (end > 0 && nums[end] == nums[start]){
            end--;
        }

        int cmpTarget = nums[end];

        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (nums[mid] > cmpTarget){
                start = mid;
            } else {
                end = mid;
            }
        }

        return Math.min(nums[start], nums[end]);
    }
}

 

以上是关于lintcode160- Find Minimum in Rotated Sorted Array II- medium的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Find Minimum in Rotated Sorted Array II

[LintCode] 159 Find Minimum in Rotated Sorted Array

lintcode159- Find Minimum in Rotated Sorted Array- medium

Lintcode: Interval Minimum Number

lintcode-medium-Minimum Adjustment Cost

lintcode-medium-Minimum Window Substring