LeetCode Python算法算法提高之LeetCode刷题LeetCode

852. Peak Index in a Mountain Ar

2018-06-21  本文已影响2人  fred_33c7

题目地址: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

注意

上一篇 下一篇

猜你喜欢

热点阅读