lintcode 寻找旋转排序数组中的最小值

来源:互联网 发布:淘宝内衣模特 亚男 编辑:程序博客网 时间:2024/04/19 21:02

假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7可能变成是4 5 6 7 0 1 2)。

你需要找到其中最小的元素。

你可以假设数组中不存在重复的元素。

样例

给出[4,4,5,6,7,0,1,2]  返回 0

分析:有序的用二分查找比较高效, 最坏的时间复杂度为O(n),二分查找的核心是缩小查找范围,这里当nums[right]<nums[mid]时,最小值一定在mid+1(mid可以排除)和right之间。

public class Solution { /**     * @param nums: a rotated sorted array     * @return: the minimum number in the array     */    public static int findMin(int[] nums) {        // write your code here    int l = 0;        int r = nums.length-1;             while(l<r){        int mid = (l+r)/2;        if(nums[r]<nums[mid]){        l = mid+1;        }        else{        r = mid;                }        }         return nums[l];    }}


0 0