-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode162-find-peak-element.cpp
60 lines (52 loc) · 1.23 KB
/
leetcode162-find-peak-element.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// https://leetcode.com/problems/find-peak-element/
class Solution {
public:
bool isPeak(vector<int>& nums, int pos) {
// edge cases:
if (pos < 1) {
// compare w/ pos+1
if (nums[pos] > nums[pos+1])
return true;
else
return false;
}
else if (pos > nums.size() - 2) {
// compare w/ pos - 1
if (nums[pos] > nums[pos-1])
return true;
else
return false;
}
else {
if (nums[pos] > nums[pos-1] && nums[pos] > nums[pos+1])
return true;
else
return false;
}
}
int calcMid(int left, int right) {
return left + (right - left)/2;
}
int findPeakElement(vector<int>& nums) {
int peakIdx = -1;
int length = nums.size();
int left = 0, right = length - 1;
int currIdx = calcMid(left, right);
// edge cases
if (length == 1)
return 0;
if (isPeak(nums, 0))
return 0;
if (isPeak(nums, length - 1))
return length - 1;
while(!isPeak(nums, currIdx)) {
if (nums[currIdx] < nums[currIdx+1])
left = currIdx;
else
right = currIdx;
currIdx = calcMid(left, right);
}
peakIdx = currIdx;
return peakIdx;
}
};