/**
* @param {number[]} nums
* @return {number}
*/
var findPeakElement = function(nums) {
if (nums.length === 1) return 0;
let left = 0, right = nums.length - 1;
while (left + 1 < right) {
let mid = Math.round((left + right) / 2);
// for simplicity, take left, mid and right values from array, or use -Infinity if value is outside of nums array length
let m = nums[mid];
let l = nums[mid - 1] ? nums[mid - 1] : -Infinity;
let r = nums[mid + 1] ? nums[mid + 1] : -Infinity;
if (m > l && m > r) {
return mid;
}
if (r > m) {
left = mid;
} else if (l > m) {
right = mid;
}
}
if (nums[right] > nums[left]) {
if (!nums[right + 1] || nums[right] > nums[right + 1]) {
return right;
}
}
if (nums[left] > nums[right]) {
if (!nums[left - 1] || nums[left] > nums[left - 1]) {
return left;
}
}
// should never happen
console.log('bad input', nums);
return -1;
};
let arr = [1,3,2,1];
console.log('expected: 1, calculated:',findPeakElement(arr));
/*
Template 3
Initial Condition: left = 0, right = length-1
Termination: left + 1 == right
Searching Left: right = mid
Searching Right: left = mid
*/
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.