Maximum Number in Mountain Sequence

Given a mountain sequence ofnintegers which increase firstly and then decrease, find the mountain top.

解析 :

这道题跟rotated sorted array不一样,不能用中间值和最后值比较来判断哪部分是有序。

我们只需要通过比较mid和mid+1的大小来判断mid是处于上坡还是下坡。

class Solution:
    # @param {int[]} nums a mountain sequence which increase firstly and then decrease
    # @return {int} then mountain top
    def mountainSequence(self, nums):
        # Write your code here
        # return max(nums)
        start = 0
        end = len(nums)-1
        while start + 1 < end:
            mid = (start+end)/2
            # find out if on downhill or uphill
            # uphill
            if nums[mid] < nums[mid+1]:
                start = mid
            # downhill
            else:
                end = mid
        if nums[start]>nums[end]:
            return nums[start]
        return nums[end]

Last updated

Was this helpful?