LeetCode: Find Peak Element Solution
Divide and conquerApproach
Start with the mid
of range [left, right]
Compare nums[mid]
with two adjacent elements
- if fits,
mid
is the result - if not fit, shorten the range
Implementation
1/**2 * @param {number[]} nums3 * @return {number}4 */5var findPeakElement = function (nums) {6 const recursion = (left, right) => {7 const mid = Math.floor((left + right) / 2)8 if (nums[mid] < nums[mid - 1]) {9 return recursion(left, mid - 1)10 } else if (nums[mid] < nums[mid + 1]) {11 return recursion(mid + 1, right)12 } else {13 return mid14 }15 }1617 return recursion(0, nums.length - 1)18}
References
Algorithmic Thinking, Peak Finding (MIT 6.006 Introduction to Algorithms, Fall 2011, Part 1)
Comments
Loading comments...
Tags
leetcode
recursion
binary search
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Lowest Common Ancestor of a Binary Search Tree
Recursive approach
Previous Post
CSSBattle 1.9: Tesseract
Stack, rotate