码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode : Find Minimum in Rotated Sorted Array

时间:2016-03-13 00:25:32      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    /**
     * @param num: a rotated sorted array
     * @return: the minimum number in the array
     */
    public int findMin(int[] num) {
        // write your code here
        // handle corner case
        // the idea is to find the [first] element less than num[num.length - 1]
        if (num == null || num.length == 0) {
            return -1;
        }
        int start = 0, end = num.length - 1;
        int target = num[end];
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int current = num[mid];
            if (current > target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        // decide which to choose
        if (num[start] < target) {
            return num[start];
        }
        return num[end];
    }
}

  使用二分搜索来做,基本思想就是: find the first element less than num[num.length - 1],至于为什么要这样,画个图就知道了后一段的数肯定要比前一段的数小。

LintCode : Find Minimum in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/dingjunnan/p/5270851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!