您的当前位置:首页正文

Maximum Number in Mountain Seque

来源:图艺博知识网

题目

 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

答案

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
        start, end = 0, len(nums) - 1
        while(start + 1 < end):
            left = start + (end - start) / 2
            right = end -  (end - left) / 2
            
            if(nums[left] < nums[right]):
                start = left + 1 
            elif nums[left] > nums[right]:
                end = right - 1
            else:
                start = left 
                end = right
        
        return max(nums[start],nums[end])
IMG_1225.JPG
Top