competitive-programmingDec 29, 20211 min read
[LeetCode] 162. Find Peak Element Explained
Updated: Dec 29, 2021
Binary search
Available in:enko
#Problem
#Approach
Use binary search to compare with the values on either side.
- If :
a exists to the left of index .
r <- m;
- If :
a exists to the right of index .
l <- m+1;
- If neither holds: index itself is a .
return m;
#Code

/**
* written: 2021. 12. 29. Wed. 16:05:01 [UTC+9]
* jooncco의 mac에서.
**/
typedef vector<int> vi;
class Solution {
public:
int findPeakElement(vi &nums) {
int n= nums.size();
// nums[-1]과 nums[n]이 -∞ 이므로 size가 1이면 자체가 peak
if (n == 1) return 0;
int l= 0, r= n-1;
while (l < r) {
int m= l+(r-l)/2;
if (m > 0 && nums[m] < nums[m-1]) r= m;
else if (m < n-1 && nums[m] < nums[m+1]) l= m+1;
else return m; // peak를 찾았으니 바로 return.
}
// l == peak index
return l;
}
};
#Complexity
- Time:
- Space: