网站主要盈利模式,东莞常平镇邮政编码,网络公关公司,苏州钻木网络科技有限公司一、73. 矩阵置零 73. 矩阵置零 - 力扣#xff08;LeetCode#xff09; 1. 解题思路
1. 使用两个数组分别标记每行每列是否有0#xff0c;初始化全为False#xff0c;遇到0就变成True。
2. 遍历矩阵#xff0c;遇到0就将False改成True。
3. 再次遍历矩阵#xff0c;更…一、73. 矩阵置零 73. 矩阵置零 - 力扣LeetCode 1. 解题思路
1. 使用两个数组分别标记每行每列是否有0初始化全为False遇到0就变成True。
2. 遍历矩阵遇到0就将False改成True。
3. 再次遍历矩阵更新原数组将0的行列置为0。 2. 代码实现
class Solution:def setZeroes(self, matrix: List[List[int]]) - None:Do not return anything, modify matrix in-place instead.m, n len(matrix), len(matrix[0])row, col [False]*m, [False]*nfor i in range(m):for j in range(n):if matrix[i][j] 0:row[i] col[j] Truefor i in range(m):for j in range(n):if row[i] or col[j]:matrix[i][j] 0
二、54.螺旋矩阵 54. 螺旋矩阵 - 力扣LeetCode 1. 解题思路
1判断传入的矩阵是否具备合法性不合法就直接返回空数组。
2定义res空数组用于存储最终的结果。
3定义四个变量分别是矩阵的四个边界。 2. 代码实现
class Solution:def spiralOrder(self, matrix: List[List[int]]) - List[int]:if not matrix or not matrix[0]:return []res []left,right 0, len(matrix[0])-1top, bottom 0, len(matrix)-1while left right and top bottom:for i in range(left, right1):res.append(matrix[top][i])for i in range(top1, bottom1):res.append(matrix[i][right])if left right and top bottom:for i in range(right-1, left, -1):res.append(matrix[bottom][i])for i in range(bottom, top, -1):res.append(matrix[i][left])left 1right - 1top 1bottom - 1return res
三、48.旋转图像
1. 解题思路
1使用逐层旋转的方法由于是n*n的矩阵所以只需要定义left和right的初始值即可: left, right 0, len(matrix)。left和right初始值分别直接赋值给top和bottom即可。
2定义一个单独的变量topleft用于存储左上角的数值方便后面进行交换。
3逐层进行旋转也就是先逐次旋转四个顶点也就是进行值的交换然后旋转偏移量为i的元素。
2. 代码实现
class Solution:def rotate(self, matrix: List[List[int]]) - None:left, right 0, len(matrix)-1while left right:for i in range(right-left):top, bottom left, righttopleft matrix[top][lefti]matrix[top][lefti] matrix[bottom-i][left]matrix[bottom-i][left] matrix[bottom][right-i]matrix[bottom][right-i] matrix[topi][right]matrix[topi][right] topleftleft1right-1