我们把符合下列属性的数组 A 称作山脉:
A.length >= 3
存在 0 < i < A.length - 1 使得A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 的 i 的值。
示例 1:
输入:[0,1,0]
输出:1
示例 2:
输入:[0,2,1,0]
输出:1
提示:
3 <= A.length <= 10000
0 <= A[i] <= 10^6
A 是如上定义的山脉
函数命名:
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
解答:
# 二分查找 时间复杂度logn的版本
def peakIndexInMountainArray(mountain):
height = len(mountain)
low = 0
while low <= height:
mid = (height + low) // 2
if array[mid] > array[mid - 1] and array[mid] > array[mid + 1]:
print(mid)
break
elif array[mid] > array[mid + 1]:
height = mid - 1
else:
low = mid + 1
array = [0, 1, 0]
peakIndexInMountainArray(array)
array = [0, 2, 1, 0]
peakIndexInMountainArray(array)
array = [0, 1, 2, 3, 7, 6, 5, 4, 2, 1, 0]
peakIndexInMountainArray(array)
array = [0, 1, 2, 7, 6, 5, 4, 0]
peakIndexInMountainArray(array)