LeetCode 题解工作台
对角线遍历 II
给你一个列表 nums ,里面每一个元素都是一个整数列表。请你依照下面各图的规则,按顺序返回 nums 中对角线上的整数。 示例 1: 输入: nums = [[1,2,3],[4,5,6],[7,8,9]] 输出: [1,4,2,7,5,3,8,6,9] 示例 2: 输入: nums = [[1,…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·排序
答案摘要
我们观察到: - 每一条对角线上的 $i + j$ 的值都是相同的;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个列表 nums ,里面每一个元素都是一个整数列表。请你依照下面各图的规则,按顺序返回 nums 中对角线上的整数。
示例 1:

输入:nums = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,4,2,7,5,3,8,6,9]
示例 2:

输入:nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] 输出:[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
示例 3:
输入:nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]] 输出:[1,4,2,5,3,8,6,9,7,10,11]
示例 4:
输入:nums = [[1,2,3,4,5,6]] 输出:[1,2,3,4,5,6]
提示:
1 <= nums.length <= 10^51 <= nums[i].length <= 10^51 <= nums[i][j] <= 10^9nums中最多有10^5个数字。
解题思路
方法一:排序
我们观察到:
- 每一条对角线上的 的值都是相同的;
- 下一条对角线的 的值比前一条对角线的大;
- 在同一条对角线中的 是相同的,而 值是从小到大递增。
因此,我们将所有数字以 的形式存进 ,然后按照前两项排序。最后返回 所有元素下标为 的值组成的数组即可。
时间复杂度 ,其中 是数组 中元素的个数。空间复杂度 。
class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
arr = []
for i, row in enumerate(nums):
for j, v in enumerate(row):
arr.append((i + j, j, v))
arr.sort()
return [v[2] for v in arr]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each element is processed once, and sorting within small diagonals does not exceed O(n) in total. Space complexity is O(\sqrt{n}) because the number of diagonals in a jagged 2D array is bounded by roughly the square root of the total elements. |
| 空间 | O(\sqrt{n}) |
面试官常问的追问
外企场景- question_mark
Expect candidates to identify the diagonal index pattern using row + column sums.
- question_mark
Watch for correct handling of jagged arrays with varying row lengths.
- question_mark
Candidates should optimize for O(n) traversal without unnecessary nested loops.
常见陷阱
外企场景- error
Misaligning elements when rows have different lengths causing wrong diagonal grouping.
- error
Sorting each diagonal incorrectly, reversing intended order from bottom to top.
- error
Using extra nested loops instead of mapping diagonal indices, leading to O(n^2) complexity.
进阶变体
外企场景- arrow_right_alt
Diagonal Traverse III with dynamic row additions mid-traversal.
- arrow_right_alt
Reverse Diagonal Traversal returning diagonals from bottom-right to top-left.
- arrow_right_alt
Weighted Diagonal Traversal applying transformations to elements while maintaining diagonal order.