LeetCode 题解工作台
对角线遍历
给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。 示例 1: 输入: mat = [[1,2,3],[4,5,6],[7,8,9]] 输出: [1,2,4,7,5,3,6,8,9] 示例 2: 输入: mat = [[1,2],[3,4]] 输…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·matrix
答案摘要
对于每一轮 ,我们固定从右上方开始往左下方遍历,得到 。如果 为偶数,再将 逆序。然后将 添加到结果数组 中。 问题的关键在于确定轮数以及每一轮的起始坐标点 $(i, j)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。
示例 1:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,4,7,5,3,6,8,9]
示例 2:
输入:mat = [[1,2],[3,4]] 输出:[1,2,3,4]
提示:
m == mat.lengthn == mat[i].length1 <= m, n <= 1041 <= m * n <= 104-105 <= mat[i][j] <= 105
解题思路
方法一:定点遍历
对于每一轮 ,我们固定从右上方开始往左下方遍历,得到 。如果 为偶数,再将 逆序。然后将 添加到结果数组 中。
问题的关键在于确定轮数以及每一轮的起始坐标点 。
时间复杂度 。其中 和 分别为矩阵的行数和列数。忽略答案的空间消耗,空间复杂度 。
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
m, n = len(mat), len(mat[0])
ans = []
for k in range(m + n - 1):
t = []
i = 0 if k < n else k - n + 1
j = k if k < n else n - 1
while i < m and j >= 0:
t.append(mat[i][j])
i += 1
j -= 1
if k % 2 == 0:
t = t[::-1]
ans.extend(t)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(M*N) as each element is visited exactly once. Space complexity is O(1) extra if output array is not counted; using only loop variables and flags. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidate starts by recognizing the diagonal index sum pattern.
- question_mark
Candidate correctly alternates traversal direction per diagonal.
- question_mark
Candidate efficiently handles matrix boundaries without errors.
常见陷阱
外企场景- error
Incorrectly reversing elements on diagonals leading to wrong order.
- error
Off-by-one errors when accessing the last row or column.
- error
Using extra space unnecessarily instead of in-place collection into the result array.
进阶变体
外企场景- arrow_right_alt
Traverse diagonals starting from bottom-right instead of top-left.
- arrow_right_alt
Return only the elements of even-numbered diagonals.
- arrow_right_alt
Perform the traversal but output each diagonal as a separate subarray instead of flattening.