参考:
https://leetcode-cn.com/problems/peak-index-in-a-mountain-array/solution/shan-mai-shu-zu-de-feng-ding-suo-yin-by-dtqvv/
二分法查找:
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]:
return mid
if arr[mid] < arr[mid - 1]:
right = mid
if arr[mid] < arr[mid + 1]:
left = mid
return -1
```
class Solution:
def peakIndexInMountainArray(self, A) -> int:
max_num = -1
max_index = -1
for i in range(len(A)):
if A[i]>max_num:
max_index = i
max_num = A[i]
else:
break
return max_index
```
package T852山脉数组的峰顶索引;
public class Solution {
public int peakIndexInMountainArray(int[] A) {
int max = -1;
int index = -1;
for (int i = 0; i < A.length; i++) {
if (A[i] > max) {
max = A[i];
index = i;
} else {
return index;
}
}
return 0;
}
}