原题链接:852. 山脉数组的峰顶索引
solution: 二分查找
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int n = arr.size();
int l=0,r=n-1;
while(l<r){
int mid=l+r>>1;
if(arr[mid]>arr[mid+1]) r=mid;
else if(arr[mid]<arr[mid+1]) l=mid+1;
}
return l;
}
};
找第一个逆序的数:
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int n = arr.size();
int res=0;
for(int i=1;i<n;i++){
if(arr[i]<arr[i-1]){
res = i-1;
break;
}
}
return res;
}
};