LeetCode 题解工作台

找出峰值

给你一个下标从 0 开始的数组 mountain 。你的任务是找出数组 mountain 中的所有 峰值 。 以数组形式返回给定数组中 峰值 的下标, 顺序不限 。 注意: 峰值 是指一个严格大于其相邻元素的元素。 数组的第一个和最后一个元素 不 是峰值。 示例 1: 输入: mountain = …

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·结合·enumeration

bolt

答案摘要

我们直接遍历下标 $i \in [1, n-2]$,对于每个下标 ,如果满足 $mountain[i-1] < mountain[i]$ 并且 $mountain[i + 1] < mountain[i]$,那么 就是一个峰值,我们将下标 加入答案数组中。 遍历结束后,返回答案数组即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·结合·enumeration 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的数组 mountain 。你的任务是找出数组 mountain 中的所有 峰值

以数组形式返回给定数组中 峰值 的下标,顺序不限

注意:

  • 峰值 是指一个严格大于其相邻元素的元素。
  • 数组的第一个和最后一个元素 是峰值。

 

示例 1:

输入:mountain = [2,4,4]
输出:[]
解释:mountain[0] 和 mountain[2] 不可能是峰值,因为它们是数组的第一个和最后一个元素。
mountain[1] 也不可能是峰值,因为它不严格大于 mountain[2] 。
因此,答案为 [] 。

示例 2:

输入:mountain = [1,4,3,8,5]
输出:[1,3]
解释:mountain[0] 和 mountain[4] 不可能是峰值,因为它们是数组的第一个和最后一个元素。
mountain[2] 也不可能是峰值,因为它不严格大于 mountain[3] 和 mountain[1] 。
但是 mountain[1] 和 mountain[3] 严格大于它们的相邻元素。
因此,答案是 [1,3] 。

 

提示:

  • 3 <= mountain.length <= 100
  • 1 <= mountain[i] <= 100
lightbulb

解题思路

方法一:直接遍历

我们直接遍历下标 i[1,n2]i \in [1, n-2],对于每个下标 ii,如果满足 mountain[i1]<mountain[i]mountain[i-1] < mountain[i] 并且 mountain[i+1]<mountain[i]mountain[i + 1] < mountain[i],那么 mountain[i]mountain[i] 就是一个峰值,我们将下标 ii 加入答案数组中。

遍历结束后,返回答案数组即可。

时间复杂度 O(n)O(n),其中 nn 是数组的长度。忽略答案数组的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def findPeaks(self, mountain: List[int]) -> List[int]:
        return [
            i
            for i in range(1, len(mountain) - 1)
            if mountain[i - 1] < mountain[i] > mountain[i + 1]
        ]
speed

复杂度分析

指标
时间complexity is O(n) because each internal element is visited once. Space complexity is O(k) where k is the number of peaks, for storing their indices. No extra arrays are needed for computation.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate must correctly skip boundary elements.

  • question_mark

    Check if candidate uses strict greater-than comparison, not greater-than-or-equal.

  • question_mark

    Efficient single-pass iteration signals understanding of array enumeration pattern.

warning

常见陷阱

外企场景
  • error

    Including first or last element as a peak incorrectly.

  • error

    Using >= instead of >, leading to wrong peaks in flat regions.

  • error

    Neglecting neighbor comparisons and returning indices blindly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return peaks in ascending or original index order instead of any order.

  • arrow_right_alt

    Find local minima instead of peaks using similar neighbor comparison logic.

  • arrow_right_alt

    Handle arrays with repeated elements by ignoring flat peaks between equal neighbors.

help

常见问题

外企场景

找出峰值题解:数组·结合·enumeration | LeetCode #2951 简单