【算法练习】852. 山脉数组的峰顶索引
题目链接:852. 山脉数组的峰顶索引
根据题目用复杂度用O(long n)的方法解决问题,我们可以想到用二分查找解决:
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int left=0,right=arr.size()-1;
while(left <= right)
{
//如果大于右边说明山峰在左边,小于右边边说明山峰在右边
int mid = left+(right-left)/2;
if(arr[mid] < arr[mid+1])
{
left = mid+1;
}
else if(arr[mid] > arr[mid+1])
{
right = mid - 1;
}
}
return left;
}
};