Skip to content

Commit b3d5f12

Browse files
committed
Update 162_Find_Peak_Element.cpp
1 parent 9ae92b7 commit b3d5f12

File tree

1 file changed

+36
-39
lines changed

1 file changed

+36
-39
lines changed

C/162_Find_Peak_Element.cpp

Lines changed: 36 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,52 @@
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
1+
/*
2+
A peak element is an element that is greater than its neighbors.
3+
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
4+
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
5+
You may imagine that num[-1] = num[n] = -∞.
6+
7+
Example:
8+
in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
9+
10+
Tag: Array, Binary Search
11+
12+
Author: Xinyu Liu
13+
*/
1214

1315
#include <iostream>
1416
#include <vector>
1517
using namespace std;
1618

17-
18-
1919
class Solution {
2020

2121
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-
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+
if (nums.at(i-1) < nums.at(i) & nums.at(i) > nums.at(i+1))
34+
return i;
3935
}
36+
return -1;
37+
}
4038
};
4139

42-
void main(){
43-
40+
void main(int argc, char ** argv){
4441

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) );
42+
// Initialize vector
43+
int myints[] = {1,2,3,4,3};
44+
int index;
45+
std::vector<int> test (myints, myints + sizeof(myints) / sizeof(int) );
4946

50-
Solution sol;
51-
index = sol.findPeakElement (test);
47+
Solution sol;
48+
index = sol.findPeakElement (test);
5249

53-
printf("%i \n",index);
50+
printf("%i \n",index);
5451

5552
}

0 commit comments

Comments
 (0)