[LeetCode] Find Peak Element

162. Find Peak Element

A peak element is an element that is strictly greater than its neighbors.

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞.

You must write an algorithm that runs in O(log n) time.

  • new solution update 2022.02.23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int getOrDefault(vector<int>& nums, int i, int def = INT_MIN) {
if(i < 0 or i >= nums.size())
return def;
return nums[i];
}
public:
int findPeakElement(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while(l < r) {
int m = l + (r - l) / 2;
int left = getOrDefault(nums, m - 1);
int right = getOrDefault(nums, m + 1);
if(nums[m] > left and nums[m] > right) return m;
else if(left > right) r = m - 1;
else l = m + 1;

}
return l;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int l(0), r(nums.size() - 1);
while(l < r) {
int m = (l + r) / 2;
if(nums[m] > nums[m + 1]) r = m;
else l = m + 1;
}
return l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/04/PS/LeetCode/find-peak-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.