Maximum Number in Mountain Sequence

题目

 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容