-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetZeroes.go
More file actions
106 lines (95 loc) · 2.07 KB
/
Copy pathsetZeroes.go
File metadata and controls
106 lines (95 loc) · 2.07 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* https://leetcode.com/problems/set-matrix-zeroes/description/
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
*/
package larray
func setZeroes(matrix [][]int) {
if len(matrix) == 0 {
return
}
setColZero := func(matrix [][]int, col int) {
for i := range matrix {
matrix[i][col] = 0
}
}
setRowZero := func(matrix [][]int, row, col int) {
matrix[row][col] = 0 // cur
// ago
for j := col - 1; j >= 0; j-- {
if matrix[row][j] == 0 &&
((row-1 >= 0 && matrix[row-1][j] != 0) ||
(row+1 < len(matrix) && matrix[row+1][j] != 0)) {
break
}
matrix[row][j] = 0
}
}
m, n := len(matrix), len(matrix[0])
cols := make([]bool, 2, 2) // index --> col now-2, now-1 isNeedSetZero
// init col index 0
for i := 0; i < m; i++ {
if matrix[i][0] == 0 {
cols[1] = true
break
}
}
// deal col index j
for j := 1; j < n; j++ {
// first deal col - 2
if cols[0] {
setColZero(matrix, j-2)
cols[0] = false
}
cols[0], cols[1] = cols[1], cols[0]
for i := 0; i < m; i++ {
if matrix[i][j] == 0 && !cols[1] {
cols[1] = true
}
// now can safe setZero row before curRow
if matrix[i][j] == 0 || matrix[i][j-1] == 0 {
setRowZero(matrix, i, j)
}
}
}
for i, flag := range cols {
if col := n - 2 + i; flag && col >= 0 {
setColZero(matrix, col)
}
}
}
/* O(m + n) space
func setZeroes(matrix [][]int) {
if len(matrix) == 0 {
return
}
m, n := len(matrix), len(matrix[0])
rows := make([]bool, m, m)
cols := make([]bool, n, n)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
rows[i] = true
cols[j] = true
}
}
}
for i := 0; i < m; i++ {
if rows[i] {
for j := range matrix[i] {
matrix[i][j] = 0
}
}
}
for j := 0; j < n; j++ {
if cols[j] {
for i := range matrix {
matrix[i][j] = 0
}
}
}
}
*/