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
    原文作者:fred_33c7
    原文地址: https://www.jianshu.com/p/a2e97ae24afe
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞