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

来源:互联网 发布:数控编程g71 编辑:程序博客网 时间:2024/04/27 09:51

假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
你可以假设数组中不存在重复的元素。
样例
给出[4,5,6,7,0,1,2] 返回 0

解题思路:二分查找。
一刷ac

public class Solution {    /**     * @param num: a rotated sorted array     * @return: the minimum number in the array     */    public int findMin(int[] num) {        if(num == null || num.length == 0) return 0;        int low = 0;        int high = num.length - 1;        int res = num[low];        while(low + 1 <  high){            if(num[low] < num[high]) break;            if(num[(low+high)/2] > num[low]){                low = (low+high)/2 + 1;            }else{                high = (low+high)/2;            }        }        res = Math.min(num[low], num[high]);        return res;    }}

优化一下

public class Solution {    /**     * @param num: a rotated sorted array     * @return: the minimum number in the array     */    public int findMin(int[] num) {        if(num == null || num.length == 0) return 0;        int left = 0;        int right = num.length - 1;        while(left < right){            int mid = (left + right) / 2;            if(num[mid] > num[right]){                left = mid + 1;            }else{                right = mid;            }        }        return num[left];    }}
0 0
原创粉丝点击