lintcode585- Maximum Number in Mountain Sequence- medium

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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];

    }
}

 

以上是关于lintcode585- Maximum Number in Mountain Sequence- medium的主要内容,如果未能解决你的问题,请参考以下文章

LintCode: Maximum Depth of Binary Tree

lintcode-medium-Maximum Subarray II

lintcode-easy-Maximum Depth of Binary Tree

[LintCode] Maximum Subarray 最大子数组

[LintCode] Maximum Gap 求最大间距

lintcode-medium-Binary Tree Maximum Path Sum