时间:2020-6-18
题目地址:https://leetcode-cn.com/problems/diagonal-traverse/
题目难度:Medium
题目描述:
给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。
示例:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,4,7,5,3,6,8,9]
解释:
说明:
给定矩阵中的元素总数不会超过 100000 。
思路1:
偶数行是每次行减列加,奇数行是每次行加列减;
偶数行到边界时需要考虑如果后边还有列就加列,没有的话就加行【换到递减的行】,奇数行相反,到边界时需要考虑后边还有行就加行,没有的话就加列【换到递减的列】
参考下图示
代码段1:通过
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
if(len(matrix) == 0): return None
row, col = len(matrix), len(matrix[0])
number = 2 * min(row, col) - 1 + max(row, col) - min(row, col)
result = []
now_row, now_col = 0, 0
for i in range(number):
while(now_row <= row - 1 and now_col <= col - 1 and now_row >= 0 and now_col >= 0):
if(i % 2 == 0):
result.append(matrix[now_row][now_col])
now_row -= 1
now_col += 1
else:
result.append(matrix[now_row][now_col])
now_row += 1
now_col -= 1
if(i % 2 == 0):
now_row += 1
now_col -= 1
if(now_col + 1 <= col - 1):
now_col += 1
else:
now_row += 1
else:
now_row -= 1
now_col += 1
if(now_row + 1 <= row - 1):
now_row += 1
else:
now_col += 1
return result
总结:
- 观察了好久找到的规律,写了一早上,我想给自己点一个大大的赞,刷题的经验,如果找不到规律就多写几个 = =,总会找的,死磕自己,奥利给
- 这代码我看都不想看,如何优化
#后续优化
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
if(len(matrix) == 0): return None
row, col = len(matrix), len(matrix[0])
number = 2 * min(row, col) - 1 + max(row, col) - min(row, col)
result = []
now_row, now_col = 0, 0
for i in range(number):
while(now_row <= row - 1 and now_col <= col - 1 and now_row >= 0 and now_col >= 0):
result.append(matrix[now_row][now_col])
if(i % 2 == 0):
now_row -= 1
now_col += 1
else:
now_row += 1
now_col -= 1
if(i % 2 == 0):
now_row += 1
now_col -= 1
if(now_col + 1 <= col - 1):
now_col += 1
else:
now_row += 1
else:
now_row -= 1
now_col += 1
if(now_row + 1 <= row - 1):
now_row += 1
else:
now_col += 1
return result
思路2:从右上到左下遍历对角线,如果是偶数逆
代码段2:通过
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
m, n, r = len(matrix), len(matrix) and len(matrix[0]), []
for l in range(m + n - 1):
temp = [matrix[i][l - i] for i in range(max(0, l + 1 - n), min(l + 1, m))]
r += temp if l % 2 else temp[::-1]
return r
总结:
- 这位大佬专门写短解法的,厉害的不行了
- 执行用时和内存消耗也很高,一味秀操作是不是也不利于团队和谐
后续优化:自己写的代码自己优化