Skip to content

Commit 4efdf54

Browse files
committed
peak in mountain array
1 parent 283beb7 commit 4efdf54

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

Searching/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
|5| [Arranging Coins(Easy)](https://leetcode.com/problems/arranging-coins/)|[Solution](arranging_coin.cpp)|
1111
|6| [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/)|[Solution](smallest_letter_greater_than_target.cpp)|
1212
|7| [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/)|[Solution](kth_missing_positive_no.cpp)|
13-
|8| [Search Insert Position](https://leetcode.com/problems/search-insert-position/)|Pending|
13+
|8| [Search Insert Position](https://leetcode.com/problems/search-insert-position/)|[Solution](search_insert_position.cpp)|
1414
|9| [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/)|Pending|
1515
|10| [Count Negative Numbers in a Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/)|Pending|
1616
|11| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)|Pending|

Searching/peak_in_mountain_array.cpp

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

0 commit comments

Comments
 (0)