Skip to content

Commit d8cdc68

Browse files
authored
Create PeakFinding.js
Iterative O(n) peakfinding algorithm
1 parent 4f49050 commit d8cdc68

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

Array/PeakFinding.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var findPeakElement = function(nums) {
6+
if(nums.length == 1) return 0
7+
for(let i=0; i <nums.length; i++){
8+
if(nums[i] >= nums[i-1] && nums[i] >= nums[i+1]){
9+
return i
10+
}
11+
if(i == 0 && nums[i] >= nums[i+1]){
12+
return i
13+
}
14+
if(i == nums.length-1 && nums[i] >= nums[i-1]){
15+
return i
16+
}
17+
}
18+
};
19+
20+
//iterate through the array and for each element check its left neighbor and right neighbor
21+
//if the element is larger than or equal to both neighbors return that number

0 commit comments

Comments
 (0)