-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindPeakElement.js
52 lines (49 loc) · 1.24 KB
/
findPeakElement.js
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
// 162 Find Peak Element
// 852. Peak Index in a Mountain Array
// https://leetcode.com/problems/find-peak-element/description/
// https://leetcode.com/problems/peak-index-in-a-mountain-array/description/
/**
* @param {number[]} nums
* @return {number}
*/
const findPeakElement = function(nums) {
let l = 0;
let r = 1;
let peak = -Infinity;
let peakIndex = 0;
if(nums.length === 1) return 0;
if(nums.length < 3) {
if(nums[0] > nums[1]) {
return 0
} else {
return 1
}
}
if(nums[0]>nums[1]) return 0;
if(nums[nums.length-1] > nums[nums.length-2]) return nums.length-1;
while(r<nums.length-1) {
if(nums[l] < nums[r] && nums[r] > nums[r+1]) {
const currPeak = Math.max(nums[r], peak);
if(currPeak !== peak) {
peakIndex = r;
}
}
r++;
l++;
}
return peakIndex;
};
// more optimised
const findPeakElement1 = (nums) => {
let l =0;
let r = nums.length -1;
while(l<r) {
let mid = Math.floor((l+r)/2);
if(nums[mid] > nums[mid+1]) {
r = mid;
} else {
l = mid+1;
}
}
return l
}