Skip to content

Commit 445a36f

Browse files
author
weiy
committed
set matrix zero medium
1 parent b820256 commit 445a36f

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed

Diff for: Array/SetMatrixZeroes.py

+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
"""
2+
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
3+
4+
Example 1:
5+
6+
Input:
7+
[
8+
[1,1,1],
9+
[1,0,1],
10+
[1,1,1]
11+
]
12+
Output:
13+
[
14+
[1,0,1],
15+
[0,0,0],
16+
[1,0,1]
17+
]
18+
Example 2:
19+
20+
Input:
21+
[
22+
[0,1,2,0],
23+
[3,4,5,2],
24+
[1,3,1,5]
25+
]
26+
Output:
27+
[
28+
[0,0,0,0],
29+
[0,4,5,0],
30+
[0,3,1,0]
31+
]
32+
Follow up:
33+
34+
1. A straight forward solution using O(mn) space is probably a bad idea.
35+
2. A simple improvement uses O(m + n) space, but still not the best solution.
36+
3. Could you devise a constant space solution?
37+
38+
若某点为 0 则此行与此列均设为0。
39+
40+
关键字:
41+
1. 坐标去重。
42+
2. 坐标标记。
43+
3. 利用原来的空间进行标记。
44+
45+
1. 先说去重,去重是我想到的第一种思路:
46+
利用set的O(1) 特性去去重,将坐标转换为字符串,然后在转换回去。
47+
48+
这个的效率正如 进阶的 1 所说,O(mn) 空间,bad idea.
49+
50+
能 beat 20% 左右。
51+
52+
2. 坐标标记
53+
x x
54+
x [0,1,2,0],
55+
[3,4,5,2],
56+
[1,3,1,5]
57+
58+
只需要标记 x 和 y一整行即可,也正如进阶 2 所说,空间 O(m+n),good but not best.
59+
用这个已经可以beat 94%
60+
61+
3. 主要在于四角,稍后在更。
62+
63+
64+
测试地址:
65+
https://leetcode.com/problems/set-matrix-zeroes/description/
66+
67+
"""
68+
class Solution(object):
69+
def setZeroes(self, matrix):
70+
"""
71+
:type matrix: List[List[int]]
72+
:rtype: void Do not return anything, modify matrix in-place instead.
73+
"""
74+
# x
75+
raw_length = len(matrix[0])
76+
# y
77+
column_length = len(matrix)
78+
79+
# O(mn) 第一版.
80+
# {"12", "23", "34"}
81+
82+
# zero_xy = set()
83+
84+
# def makeXY(x, y):
85+
# xy = set()
86+
# x = str(x)
87+
# y = str(y)
88+
# for i in range(raw_length):
89+
# xy.add(','.join([str(i), y]))
90+
91+
# for i in range(column_length):
92+
# xy.add(','.join([x, str(i)]))
93+
94+
# return xy
95+
96+
# for y in range(column_length):
97+
# for x in range(raw_length):
98+
# if matrix[y][x] == 0:
99+
# zero_xy.update(makeXY(x, y))
100+
101+
# for i in zero_xy:
102+
# t = i.split(',')
103+
# matrix[int(t[1])][int(t[0])] = 0
104+
105+
# 第二版 O(M+N)
106+
# raw = []
107+
# column = []
108+
109+
# for y in range(column_length):
110+
# for x in range(raw_length):
111+
# if matrix[y][x] == 0:
112+
# raw.append(x)
113+
# column.append(y)
114+
115+
# for x in raw:
116+
# for y in range(column_length):
117+
# matrix[y][x] = 0
118+
119+
# for y in column:
120+
# for x in range(raw_length):
121+
# matrix[y][x] = 0

0 commit comments

Comments
 (0)