LeetCode: Find Peak Element Solution

Divide and conquer

Approach

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[]} nums
3 * @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 mid
14 }
15 }
16
17 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

Next Post

LeetCode: Lowest Common Ancestor of a Binary Search Tree

Jul 19, 2021

Recursive approach

Previous Post

CSSBattle 1.9: Tesseract

Jul 13, 2021

Stack, rotate

HoningJS

Search Posts