-
Notifications
You must be signed in to change notification settings - Fork 265
/
073 Set Matrix Zeroes.py
92 lines (74 loc) · 2.76 KB
/
073 Set Matrix Zeroes.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
"""
__author__ = 'Danyang'
class Solution:
def setZeroes_error(self, matrix):
"""
store the zero at the head
constant space, O(2)
:param matrix: a list of lists of integers
:return: NOTHING, MODIFY matrix IN PLACE.
"""
if not matrix:
return
m = len(matrix)
n = len(matrix[0])
for row in xrange(m):
for col in xrange(n):
if matrix[row][col]==0:
matrix[0][col]=0 # previously scanned, safe to modify
matrix[row][0]=0 # previously scanned, safe to modify
for row in xrange(m):
if matrix[row][0]==0:
for col in xrange(n):
matrix[row][col] = 0
for col in xrange(n):
if matrix[0][col]==0:
for row in xrange(m):
matrix[row][col] = 0
def setZeroes(self, matrix):
"""
store the zero at the head
constant space
:param matrix: a list of lists of integers
:return: NOTHING, MODIFY matrix IN PLACE.
"""
if not matrix:
return
m = len(matrix)
n = len(matrix[0])
# special treatment for row and col
clear_first_row = False
clear_first_col = False
for row in xrange(m):
if matrix[row][0]==0:
clear_first_col = True
for col in xrange(n):
if matrix[0][col]==0:
clear_first_row = True
for row in xrange(1, m):
for col in xrange(1, n):
if matrix[row][col]==0:
matrix[0][col] = 0 # previously scanned, safe to modify
matrix[row][0] = 0 # previously scanned, safe to modify
for row in xrange(1, m): # avoid 0 at (0, 0) affect the entire matrix
if matrix[row][0]==0:
for col in xrange(n):
matrix[row][col] = 0
for col in xrange(1, n): # avoid 0 at (0, 0) affect the entire matrix
if matrix[0][col]==0:
for row in xrange(m):
matrix[row][col] = 0
if clear_first_row:
for col in xrange(n):
matrix[0][col] = 0
if clear_first_col:
for row in xrange(m):
matrix[row][0] = 0