题目地址: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
注意:
-
/
除号python2和python3不同,middle = (low + high) // 2
需要用两个/
才能得到整数,要不然会有错误。 -
xrang()
的用法http://www.runoob.com/python/python-func-xrange.html