题目链接:https://leetcode.com/problems/find-peak-element/
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
思路:这一题不可以测试,写完就直接提交,还怕有compile error,谁知道直接A了。还有三四天就开学了,再也不能愉快的刷题了,假期二十多天刷了一百多道了,还剩150道左右,不知道这个学期能不能刷完。
这题的思路就是二分,然后分三种情况:
1. 如果当前左右的值都比他低或者为空,则这就是极高点,返回当前位置
2. 如果当前处于一个升序上,即nums[mid-1] < nums[mid] < nums[mid+1],则往右找,即left = mid +1;
3. 如果当前处于一个降序上,即nums[mid-1] > nums[mid] > nums[mid+1],则往左找,即right = mid -1;
代码如下:
class Solution { public: int findPeakElement(vector<int>& nums) { int len = nums.size(), left = 0, right = len-1; while(left <= right) { int mid = (left+right)/2; if((mid-1>0 && nums[mid-1]< nums[mid] || mid-1<0) && (mid+1<len && nums[mid+1]< nums[mid] || mid+1>=len)) return mid; if((mid-1 >= 0 && nums[mid-1] < nums[mid] || mid-1 <0) && (mid+1<len && nums[mid+1]> nums[mid])) left = mid + 1; else right = mid - 1; } return left; } };