Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

73. Set Matrix Zeroes

Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

1
2
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

1
2
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

找0的位置,行列都設0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
T: O(nˆ2), S: O(n)
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
row = set()
column = set()

for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
row.add(i)
column.add(j)
# record row and column has 0
# print(row)
# print(column)
for i in row:
for j in range(len(matrix[0])):
matrix[i][j] = 0 # set row to 0 [i] [j]
# print("r",i) # select number of row
# print("c",j) # each column
for i in column:
for j in range(len(matrix)):
matrix[j][i] = 0 # set column to 0 [j] [i]
# print("c",i) # select number of column
# print("r",j) # each row

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels