题目链接:https://leetcode-cn.com/problems/peak-index-in-a-mountain-array/
我们把符合下列属性的数组 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 是如上定义的山脉
二分查找:
1 int peakIndexInMountainArray(int* A, int ASize){ 2 int l=0,r=ASize-1; 3 while(l<=r){ 4 int mid=l+(r-l)/2; 5 if(A[mid]>A[mid+1]&&A[mid]>A[mid-1]){ 6 return mid; 7 }else if((A[mid]>A[mid+1])&&A[mid]<A[mid-1]){ 8 r=mid-1; 9 }else{ 10 l=mid+1; 11 } 12 } 13 return -1; 14 }
顺序遍历:
1 int peakIndexInMountainArray(int* A, int ASize){ 2 int index=0; 3 for(int i=1;i<ASize-1;i++){ 4 if(A[i-1]<A[i]&&A[i]>A[i+1]){ 5 index=i; 6 break; 7 } 8 } 9 return index; 10 }