LeetCode 852. Peak Index in a Mountain Array 二分
An array arr a mountain if the following properties hold:
arr.length
>= 3- There exists some i with
0 < i < arr.length - 1
such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given a mountain array arr, return the index i such that \(arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]\).
You must solve it in \(O(\log(arr.length))\) time complexity.
Solution
点击查看代码
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
left = 0
right = len(arr)-1
while left<right:
mid = left+int((right-left)/2)
if arr[mid+1]>arr[mid]:
left=mid+1
else:
right = mid
return left