LeetCode 题解工作台
寻找峰值 II
一个 2D 网格中的 峰值 是指那些 严格大于 其相邻格子(上、下、左、右)的元素。 给你一个 从 0 开始编号 的 m x n 矩阵 mat ,其中任意两个相邻格子的值都 不相同 。找出 任意一个 峰值 mat[i][j] 并 返回其位置 [i,j] 。 你可以假设整个矩阵周边环绕着一圈值为 -1…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
记 和 分别为矩阵的行数和列数。 题目要求我们寻找峰值,并且时间复杂度为 $O(m \times \log n)$ 或 $O(n \times \log m)$,那么我们可以考虑使用二分查找。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
一个 2D 网格中的 峰值 是指那些 严格大于 其相邻格子(上、下、左、右)的元素。
给你一个 从 0 开始编号 的 m x n 矩阵 mat ,其中任意两个相邻格子的值都 不相同 。找出 任意一个 峰值 mat[i][j] 并 返回其位置 [i,j] 。
你可以假设整个矩阵周边环绕着一圈值为 -1 的格子。
要求必须写出时间复杂度为 O(m log(n)) 或 O(n log(m)) 的算法
示例 1:

输入: mat = [[1,4],[3,2]] 输出: [0,1] 解释: 3 和 4 都是峰值,所以[1,0]和[0,1]都是可接受的答案。
示例 2:

输入: mat = [[10,20,15],[21,30,14],[7,16,32]] 输出: [1,1] 解释: 30 和 32 都是峰值,所以[1,1]和[2,2]都是可接受的答案。
提示:
m == mat.lengthn == mat[i].length1 <= m, n <= 5001 <= mat[i][j] <= 105- 任意两个相邻元素均不相等.
解题思路
方法一:二分查找
记 和 分别为矩阵的行数和列数。
题目要求我们寻找峰值,并且时间复杂度为 或 ,那么我们可以考虑使用二分查找。
我们考虑第 行的最大值,不妨将其下标记为 。
如果 ,那么第 行中必然存在一个峰值,我们只需要在第 行中找到最大值即可。同理,如果 ,那么第 行中必然存在一个峰值,我们只需要在第 行中找到最大值即可。
为什么上述做法是对的?我们不妨用反证法来证明。
如果 ,假设第 行中不存在峰值,那么 不是峰值,而由于 是第 行的最大值,并且 ,那么 。我们继续从第 行往上考虑,每一行的最大值都小于上一行的最大值。那么当遍历到 时,由于矩阵中的元素都是正整数,并且矩阵周边一圈的格子的值都为 。因此,在第 行时,其最大值大于其所有相邻元素,那么第 行的最大值就是峰值,与假设矛盾。因此,第 行中必然存在一个峰值。
对于 的情况,我们可以用类似的方法证明第 行中必然存在一个峰值。
因此,我们可以使用二分查找来寻找峰值。
我们二分查找矩阵的行,初始时查找的边界为 , 。每一次,我们找到当前的中间行 ,并找到该行的最大值下标 。如果 ,那么我们就在第 行中寻找峰值,即更新 。否则,我们就在第 行中寻找峰值,即更新 。当 时,我们就找到了峰值所在的位置 。其中 是第 行的最大值下标。
时间复杂度 ,其中 和 分别为矩阵的行数和列数。二分查找的时间复杂度为 ,每次二分查找时,我们需要遍历第 行的所有元素,时间复杂度为 。空间复杂度 。
class Solution:
def findPeakGrid(self, mat: List[List[int]]) -> List[int]:
l, r = 0, len(mat) - 1
while l < r:
mid = (l + r) >> 1
j = mat[mid].index(max(mat[mid]))
if mat[mid][j] > mat[mid + 1][j]:
r = mid
else:
l = mid + 1
return [l, mat[l].index(max(mat[l]))]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on whether binary search is done on rows or columns: O(m log n) if searching columns or O(n log m) if searching rows. Space complexity is O(1) as no extra structures are needed beyond indices. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect discussion of why binary search is valid over the matrix instead of brute-force scanning.
- question_mark
Watch for whether candidates correctly identify the maximum in the middle row or column each iteration.
- question_mark
Check if they handle edge cases with single-row, single-column, or boundary elements efficiently.
常见陷阱
外企场景- error
Failing to compare the middle element with all four neighbors, missing a valid peak.
- error
Incorrectly handling equal values or assuming adjacent cells can be equal, which violates constraints.
- error
Not adjusting search direction properly when the peak is not in the current maximum column or row.
进阶变体
外企场景- arrow_right_alt
Find all peak elements instead of returning any single peak.
- arrow_right_alt
Solve on a toroidal grid where the edges wrap around instead of using a border of -1.
- arrow_right_alt
Adapt the approach for 3D matrices using similar binary search on slices.