NeetCode #273LC-162MediumBinary Search
← Back to All Problems#273 · #162 · Find Peak Element(寻找峰值)
📌 Problem Statement & Constraints
A peak element is one strictly greater than its neighbours. Given an integer array
nums, return the index of any peak. Assume nums[-1] = nums[n] = -infinity, so the boundaries can be peaks. The solution must run in O(log n). Constraints: 1 <= nums.length <= 1000, -2^31 <= nums[i] <= 2^31 - 1.💡 Core Algorithmic Approaches
- Compare
nums[mid]withnums[mid + 1]. If the sequence is rising, a peak must exist to the right; otherwise a peak is at or to the left ofmid. - This works because the virtual boundaries are
-infinity, so the array cannot be increasing everywhere. - The loop converges to a peak index in O(log n).
- Note that this does not require the array to be sorted -- only that a peak exists.
💻 Benchmark Python3 Implementation
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < nums[mid + 1]:
lo = mid + 1 # rising -> peak is to the right
else:
hi = mid # falling -> peak is at or left of mid
return lo⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log n): the range halves each iteration.
💾 Space Complexity
O(1): two indices.
⚠️ Interview Pitfalls & Follow-ups
- Using
hi = mid - 1: could skip the peak; usehi = mid. - Comparing with
nums[mid - 1]: the right neighbour is the standard choice, sincemid + 1is always in range whilemid - 1may not be. - Assuming the array is sorted: it is not; the argument only needs the boundary conditions.
- Trying to find the global maximum: any peak is acceptable, which is what makes the binary search valid.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
寻找峰值
峰值元素是指其值 严格大于 左右相邻值的元素。给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。你可以假设 nums[-1] = nums[n] = −∞ 。你必须实现时间复杂度为 O(log n) 的算法。约束:1 ≤ nums.length ≤ 1000;-2^31 ≤ nums[i] ≤ 2^31 − 1;对于所有有效的 i 都有 nums[i] != nums[i + 1] 。
核心要点
- 沿上坡方向二分(标准解) :比较 nums[mid] 与 nums[mid+1] 。若前者更小,说明处于上坡,峰值必然在右侧,令 l = mid + 1 ;否则峰值在 mid 或左侧,令 r = mid 。
- 为什么这样一定收敛到峰值 :只要 nums[mid] < nums[mid+1] ,右侧就存在至少一个峰值(因为 nums[n] = −∞ ,序列从上升转为下降时必有峰);反之左侧同理。
- 边界哨兵 :题目给出 nums[−1] = nums[n] = −∞ ,这保证了峰一定存在且二分不会越界(mid+1 最多为 n−1)。
- 复杂度 :O(log n) 时间、O(1) 空间。
常见陷阱
- 比较 nums[mid] 与 nums[mid-1] :方向相反,需要相应调整收缩逻辑;用 mid+1 更常见且不易越界。
- r = mid − 1 而非 mid : nums[mid] 本身可能是峰值,不能排除。
- 用线性扫描找第一个峰值 :O(n),不满足题目要求。
- 担心 mid+1 越界 :循环条件是 l < r ,因此 mid < r <= n−1 , mid+1 <= n−1 安全。
- 误以为数组必须严格单调 :本题允许任意波动,只要相邻元素不相等即可。
参考实现
class Solution:
def findPeakElement(self, nums: list[int]) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) // 2
if nums[mid] < nums[mid + 1]:
l = mid + 1 # 上坡 -> 峰值在右侧
else:
r = mid # 下坡 -> 峰值在左侧或就是 mid
return l