lintcode585- Maximum Number in Mountain Sequence- medium

Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top.

Example

Given nums = [1, 2, 4, 8, 6, 3] return 8
Given nums = [10, 9, 8, 7], return 10

 
用OOXX的二分法(find the first X)。特征O:nums[mid+1]-nums[mid]>0; 特征X:nums[mid+1]-nums[mid]<0。
1.中间用nums[mid+1]的时候可以直接用,因为这种while条件写法+mid总偏左本来就决定了mid最远到倒数第二个数。
 
 
public class Solution {
    /*
     * @param nums: a mountain sequence which increase firstly and then decrease
     * @return: then mountain top
     */
    public int mountainSequence(int[] nums) {

        // 要怎么处理输入???
        if (nums == null || nums.length == 0){
            throw new IllegalArgumentException();
        }

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

        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            // 应该不用判断mid < nums.length - 1把,天然的。
            // 等于情况似乎无法处理,输入应该这种描述不会给吧
            if (nums[mid + 1] - nums[mid] > 0){
                start = mid;
            } else {
                end = mid;
            }
        }

        if (nums[start] > nums[end]){
            return nums[start];
        }

        return nums[end];

    }
}

 

posted @ 2017-09-23 04:32  jasminemzy  阅读(143)  评论(0编辑  收藏  举报