Skip to content

Commit 98f52bd

Browse files
authored
Merge pull request neetcode-gh#2710 from tahzeer/patch-6
Create 0162-find-peak-element.cpp
2 parents a17f1f8 + f809626 commit 98f52bd

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

cpp/0162-find-peak-element.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(logN)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int findPeakElement(vector<int>& nums) {
7+
int n = nums.size();
8+
9+
if(n == 1) return 0;
10+
11+
int left = 0, right = n - 1;
12+
while(left <= right) {
13+
int mid = left + (right-left)/2;
14+
15+
if(mid > 0 && nums[mid] < nums[mid-1]) {
16+
right = mid - 1;
17+
}
18+
else if(mid < n-1 && nums[mid] < nums[mid+1]) {
19+
left = mid + 1;
20+
}
21+
else {
22+
return mid;
23+
}
24+
}
25+
return -1;
26+
}
27+
};

0 commit comments

Comments
 (0)