162. Find Peak Element

Leetcode

https://leetcode.com/problems/find-peak-element/

題目

A peak element is an element that is strictly greater than its neighbors.

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞.

You must write an algorithm that runs in O(log n) time.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

解答

  • 方法一

var findPeakElement = function(nums) {
    let start = 0;
    let end = nums.length - 1;
    nums[-1] = nums[nums.length] = Number.MIN_SAFE_INTEGER;
    
    while(start<=end) {
        const mid = Math.floor((start + end) / 2);
        
        if(nums[mid] > nums[mid-1] && nums[mid] > nums[mid+1])return mid;
        if(nums[mid] > nums[mid-1]) start = mid + 1;
        else end = mid;
    }
};

Runtime: 72 ms, faster than 76.14% of JavaScript online submissions for Find Peak Element.

Memory Usage: 40.4 MB, less than 6.08% of JavaScript online submissions for Find Peak Element.

測資

let nums = [1,2,1,3,5,6,4]; // 5

console.log(findPeakElement(nums))

Last updated

Was this helpful?