Skip to content

Commit 9ae92b7

Browse files
committed
C++/162_Find_Peak_Element.cpp
1 parent 1b246be commit 9ae92b7

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

C/162_Find_Peak_Element.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//A peak element is an element that is greater than its neighbors.
2+
//
3+
//Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
4+
//
5+
//The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
6+
//
7+
//You may imagine that num[-1] = num[n] = -∞.
8+
//
9+
//For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
10+
//
11+
//Author: Xinyu Liu
12+
13+
#include <iostream>
14+
#include <vector>
15+
using namespace std;
16+
17+
18+
19+
class Solution {
20+
21+
public:
22+
int findPeakElement(vector<int>& nums) {
23+
int sz = nums.size();
24+
if (sz == 1)
25+
return 0;
26+
if (nums.at(0)>nums.at(1))
27+
return 0;
28+
if (nums.at(sz-1)>nums.at(sz-2))
29+
return sz-1;
30+
31+
for(int i =1; i<nums.size();i++)
32+
{
33+
34+
if (nums.at(i-1)<nums.at(i)&nums.at(i)>nums.at(i+1))
35+
return i;
36+
}
37+
return -1;
38+
39+
}
40+
};
41+
42+
void main(){
43+
44+
45+
// Initialize vector
46+
int myints[] = {1,2,3,4,3};
47+
int index;
48+
std::vector<int> test (myints, myints + sizeof(myints) / sizeof(int) );
49+
50+
Solution sol;
51+
index = sol.findPeakElement (test);
52+
53+
printf("%i \n",index);
54+
55+
}

0 commit comments

Comments
 (0)