162. Find Peak Element
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
Note:
Your solution should be in logarithmic complexity.
方法0: brute force
Time complexity: O(n)
方法1:
思路:
这道题没有重复,且如果存在多peak,返回任意一个就可以。核心是:找到在下坡处的第一个元素(上坡的最后一个元素相对比较复杂),范围是0 到 n - 2, 如果最后不存在这样的元素,说明整个nums是个上坡,只需返回n - 1。
易错点:
- 对于这种方法, 初始点是倒数第二个点
- 要注意判断num.size() == 1
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if (nums.size() == 0) return NULL;
if (nums.size() == 1) return 0;
int size = nums.size();
int left = 0;
int right = nums.size() - 2;
while (left < right){
int mid = left + (right - left) / 2;
if (nums[mid] > nums[mid + 1]) {
right = mid;
}
else {
left = mid + 1;
}
}
if (nums[left] > nums[left + 1]){
return left;
}
return left + 1;
}
};
// NOTE: only look for local peak
// 第一个出现在local下降段的点
// 与i + 1相比,最右点特判
易错点
- 这里被简化,直接初始化right = nums.size() - 1,那么如果最后left和right相等了,说明存在,可以返回right;如果不存在,说明单增,最后一个即为所求,也就是right。
// 也可以进一步简化
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1])
left = mid + 1;
else
right = mid;
}
return right;
}
};
// left + 1 < right
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if (nums.size() == 0) return NULL;
if (nums.size() == 1) return 0;
int size = nums.size();
int left = 0;
int right = nums.size() - 2;
while (left + 1< right){
int mid = left + (right - left) / 2;
if (nums[mid] > nums[mid + 1]) {
right = mid;
}
else {
left = mid + 1;
}
}
if (nums[left] > nums[left + 1]) return left;
else if (nums[right] > nums[right + 1]) return right;
else return size - 1;
}
};
// NOTE: only look for local peak
// 第一个出现在local下降段的点
// 与i + 1相比,最右点特判