Skip to content

Commit 2242fbf

Browse files
committed
find peak element
1 parent d7d6f07 commit 2242fbf

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

Searching/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
|3| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)|Pending|
3131
|4| [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)|Pending|
3232
|5| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)|Pending|
33-
|6| [Find Peak Element](https://leetcode.com/problems/find-peak-element/)|Pending|
33+
|6| [Find Peak Element](https://leetcode.com/problems/find-peak-element/)|[Solution](peak_ele.cpp)|
3434
|7| [Find Right Interval](https://leetcode.com/problems/find-right-interval/)|Pending|
3535
|8| [Reach a Number](https://leetcode.com/problems/reach-a-number/)|Pending|
3636
|9| [Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/)|Pending|

Searching/peak_ele.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int findPeakElement(vector<int> &num)
5+
{
6+
int low = 0, high = num.size() - 1;
7+
while (low < high - 1)
8+
{
9+
int mid = (low + high) / 2;
10+
if (num[mid] > num[mid - 1] && num[mid] > num[mid + 1])
11+
return mid;
12+
else if (num[mid] > num[mid + 1])
13+
high = mid - 1;
14+
else
15+
low = mid + 1;
16+
}
17+
return num[low] > num[high] ? low : high;
18+
}
19+
20+
int main()
21+
{
22+
int n, target;
23+
cin >> n;
24+
vector<int> v;
25+
for (int i = 0; i < n; i++)
26+
{
27+
int temp;
28+
cin >> temp;
29+
v.push_back(temp);
30+
}
31+
cout << findPeakElement(v) << endl;
32+
return 0;
33+
}

0 commit comments

Comments
 (0)