Maximum Number in Mountain Sequence Lintcode

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

This question can be solved using binary search. When mid is bigger than start, there is two situation:

1. The number is increasing, and the mid is located before top.

2. The number is decreasing, the mid is located after top.

When mid is smaller than start, there is only one situation, top is in the left half.

思考的时候,可以把问题具象话,想象真的有一座山,中间的值在山的左边还是右边。考虑清楚之后,就可以舍弃一半的数了。

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) {
            return -1;
        }
        int start = 0;
        int end = nums.length - 1;
        while (start + 1 < end) {
            int mid = (end - start) / 2 + start;
            if (nums[mid] > nums[start]) {
                if (nums[mid + 1] > nums[mid]) {
                    start = mid;
                } else {
                    end = mid;
                }
            } else {
                end = mid;
            }
        }
        if (nums[start] > nums[end]) {
            return nums[start];
        }
        return nums[end];
    }
}

We don't need to check if mid + 1 is in the boundary, because start + 1 < end. Mid always < end.

posted @ 2017-03-17 05:01  璨璨要好好学习  阅读(1302)  评论(0编辑  收藏  举报