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,…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·排序

bolt

答案摘要

我们观察到: - 每一条对角线上的 $i + j$ 的值都是相同的;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个列表 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^5
  • 1 <= nums[i].length <= 10^5
  • 1 <= nums[i][j] <= 10^9
  • nums 中最多有 10^5 个数字。
lightbulb

解题思路

方法一:排序

我们观察到:

  • 每一条对角线上的 i+ji + j 的值都是相同的;
  • 下一条对角线的 i+ji + j 的值比前一条对角线的大;
  • 在同一条对角线中的 i+ji + j 是相同的,而 jj 值是从小到大递增。

因此,我们将所有数字以 (i,j,nums[i][j])(i, j, \textit{nums}[i][j]) 的形式存进 arr\textit{arr},然后按照前两项排序。最后返回 arr\textit{arr} 所有元素下标为 22 的值组成的数组即可。

时间复杂度 O(n×logn)O(n \times \log n),其中 nn 是数组 nums\textit{nums} 中元素的个数。空间复杂度 O(n)O(n)

1
2
3
4
5
6
7
8
9
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]
speed

复杂度分析

指标
时间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})
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

对角线遍历 II题解:数组·排序 | LeetCode #1424 中等