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

来源:互联网 发布:印第安保留地知乎 编辑:程序博客网 时间:2024/04/20 05:24

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

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

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

 注意事项

You may assume no duplicate exists in the array.

样例

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



/**
     * 定义两个指针,start,end,取中间值,
     * 分别与俩指针比较,决定在那边查找
 *///博客
public class Solution {
    public int findMin(int[] nums) {
        // write your code here
        int start = 0;int end = nums.length-1;
        
        while(start<end){
            if(nums[start] < nums[end]) {//没有旋转
return nums[start];
}
int mid = start + (end-start)/2;
            if(nums[start]<=nums[mid]){//只有等于才能退出,和return
                start = mid+1;
            }else {//nums[start]>nums[mid]
                end= mid;
            }
        }
        return nums[start];
    }
}