Last active
May 16, 2019 14:56
-
-
Save negarjf/4bd18eeb7443ad2563eecc0f328a31aa to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/xadewop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Find a Peak in an Array | |
* @param {number[]} nums | |
* @return {number} | |
*/ | |
var findPeakElement = function(nums) { | |
let l = nums.length - 1; | |
let half = Math.floor(l / 2); | |
if(nums[half] < nums[half + 1]){ | |
for(let i = half + 1; i <= l; i++){ | |
if(i === l){ | |
return i; | |
} | |
if(nums[i] > nums[i + 1]){ | |
return i; | |
} | |
} | |
}else if(nums[half] < nums[half - 1]){ | |
let halfArray = nums.slice(0, half); | |
for(let i = half; i >= 0; i--){ | |
if(i === 0){ | |
return 0; | |
} | |
if(nums[i] > nums[i - 1]){ | |
return i; | |
} | |
} | |
}else{ | |
return half; | |
} | |
}; | |
/** | |
* Find a Peak in an Array | |
* Better approach but not my idea :( | |
* | |
* @param {number[]} nums | |
* @return {number} | |
*/ | |
var findPeakElement = function(nums) { | |
let s = 0; | |
let e = nums.length - 1; | |
while(s < e){ | |
let mid = Math.floor((s + e) / 2); | |
if(nums[mid] < nums[mid + 1]){ | |
s = mid + 1; | |
}else{ | |
e = mid; | |
} | |
} | |
return e; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment