852. Peak Index in a Mountain Array

题目地址:https://leetcode.com/problems/peak-index-in-a-mountain-array/description/
大意:给一个峰值数列,返回峰值数的索引值

二分法

# 852. Peak Index in a Mountain Array
class Solution:
    def peakIndexInMountainArray(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        low = 0
        high = len(A) - 1
        while low < high:
            middle = (low + high) // 2
            if A[middle] < A[middle + 1]:
                low = middle +1
            else:
                high = middle
        return low

a = Solution()
print (a.peakIndexInMountainArray([0,1,0]))

答案中还给了线性查找的方法,有兴趣的可以看看:

线性查找

The mountain increases until it doesn't. The point at which it stops increasing is the peak.

class Solution(object):
    def peakIndexInMountainArray(self, A):
        for i in xrange(len(A)):
            if A[i] > A[i+1]:
                return i

注意

所有题目解题方法和答案代码地址:https://github.com/fredfeng0326/LeetCode
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容