赞
踩
给定一个 *m* x *n*
的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法**。**
示例 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]
示例 2:
输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
提示:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
def setZeroes(self, matrix: list[list[int]]) -> None: row = len(matrix) col = len(matrix[0]) row_zero = set() col_zero = set() for i in range(row): for j in range(col): if matrix[i][j] == 0: row_zero.add(i) col_zero.add(j) for i in range(row): for j in range(col): if i in row_zero or j in col_zero: matrix[i][j] = 0
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
def spiralOrder(self, matrix: list[list[int]]) -> list[int]: if not matrix: return [] rows, cols = len(matrix), len(matrix[0]) top, bottom, left, right = 0, rows - 1, 0, cols - 1 result = [] while True: # 从左到右 for j in range(left, right + 1): result.append(matrix[top][j]) top += 1 if top > bottom: break # 从上到下 for i in range(top, bottom + 1): result.append(matrix[i][right]) right -= 1 if left > right: break # 从右到左 for j in range(right, left - 1, -1): result.append(matrix[bottom][j]) bottom -= 1 if top > bottom: break # 从下到上 for i in range(bottom, top - 1, -1): result.append(matrix[i][left]) left += 1 if left > right: break return result
给定一个 n × n 的二维矩阵 matrix
表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]
示例 2:
输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
提示:
n == matrix.length == matrix[i].length
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
def rotate(self, matrix: list[list[int]]) -> None:
n = len(matrix)
# 转置矩阵
for i in range(n):
for j in range(i, n):
temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
# 翻转每一行
for i in range(n):
matrix[i].reverse()
编写一个高效的算法来搜索 *m* x *n*
矩阵 matrix
中的一个目标值 target
。该矩阵具有以下特性:
示例 1:
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
输出:true
示例 2:
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
-109 <= target <= 109
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool: if not matrix or not matrix[0]: return False rows, cols = len(matrix), len(matrix[0]) row, col = 0, cols - 1 while row < rows and col >= 0: if matrix[row][col] == target: return True elif matrix[row][col] < target: row += 1 else: col -= 1 return False
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。