Maximum Number in Mountain Sequence

01/18/2018 update
Solution:



public class Solution {
    /**
     * @param nums a mountain sequence which increase firstly and then decrease
     * @return then mountain top
     */
    public int mountainSequence(int[] nums) {
        // Write your code here
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int start = 0;
        int end = nums.length - 1;
        while (start + 1 < end) {
            int mid = (start + end) / 2;
            if (nums[mid] > nums[mid + 1]) {
                end = mid;
            } else {
                start = mid;
            }
        }
        return Math.max(nums[start], nums[end]);
    }
}
------------------------------------------------------------------------------------------------------------------------
思路:
虽然写出来通过了,但是很复杂。九章的答案很简洁。直接比较nums[mid]>nums[mid+1],如果成立则mountain在左边,否则mountain在右边。最后取nums[start] nums[end]最大的一个就好了。循环条件写成start+1 < end的好处是,最后退出的时候可以再检查一遍start和end,确保不会漏掉,而且不会有死循环。

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array