I、498. 对角线遍历(蛇形)
一、题目描述
给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。
示例:
解释:
说明:
给定矩阵中的元素总数不会超过 100000 。
二、解题思路 & 代码
2.1 对角线迭代和翻转
算法
- 初始化数组
result
,用于存储最后结果。 - 使用一个外层循环遍历所有的对角线。第一行和最后一列的元素都是对角线的起点。
- 使用一个内层 while 循环遍历对角线上的所有元素。可以计算指定对角线上的元素数量,也可以简单迭代直到索引超出范围。
- 因为不知道每条对角线上的元素数量,需要为每条对角线分配一个列表或动态数组。但是同样也可以通过计算得到当前对角线上的元素数量。
- 对于奇数编号的对角线,只需要将迭代结果翻转再加入结果数组即可。
复杂度分析
- 时间复杂度:,数组有 N 行 M 列。对于所有奇数对角线上的元素,需要两次处理,迭代和翻转。为了节省空间,需要遍历新对角线之前清除中间使用的空间,该操作需要的复杂度度,其中 K 是数组长度。因此至少处理两次数组中的元素,渐进复杂度为。
- 空间复杂度:,额外空间用于存储每条对角线的中间数组,该数组长度为 N 和 M 的最小值。注意:对角线延伸到索引超出范围结束。
2.2 模拟
算法
- 初始化一个布尔变量 direction 表示当前对角线的方向。根据当前方向和尾部位置确定下一条对角线首部。最初 direction 为 1,方向向上。每条对角线遍历完成后更新 direction。
- 假设当前对角线首部为,根据方向遍历该对角线。
1)向上的对角线,下一个元素是。
2)向下的对角线,下一个元素是。 - 遍历当前对角线元素直到到达矩阵边界结束。
- 假设现在到达当前对角线的最后一个元素,寻找下一条对角线首部。注意:下面伪代码中方向是当前对角线方向。如果当前对角线方向是向上的,则下一条对角线是向下的;否则是下一条对角线是向上的。
- 继续处理对角线元素,当前对角线遍历结束时,使用当前方向和尾部位置找出下一条对角线首部。然后翻转方向,处理下一条对角线。
复杂度分析
- 时间复杂度:,每个元素只处理一次。
- 空间复杂度:,不使用额外空间。注意:输出数组空间不计入空间复杂度,因为这是题目要求的空间。空间复杂度应该指除了最终数组以外的空间。上一个方法中是中间数组,该方法中只有几个变量。
参考:
===============================================================================================================================
II、1424. 对角线遍历 II(同向)
给你一个列表 nums ,里面每一个元素都是一个整数列表。请你依照下面各图的规则,按顺序返回 nums 中对角线上的整数。
示例 1:
示例 2:
示例 3:
示例 4:
二、解题思路 & 代码