-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode73.java
More file actions
91 lines (86 loc) · 2.75 KB
/
LeetCode73.java
File metadata and controls
91 lines (86 loc) · 2.75 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
import java.util.Arrays;
import java.util.HashSet;
import util.PrintUtil;
public class LeetCode73 {
public static void main(String[] args) {
int[][] matrix;
// 输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
// 输出:[[1,0,1],[0,0,0],[1,0,1]]
matrix = new int[][] { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } };
System.out.println(Arrays.deepToString(matrix));
new Solution73_2().setZeroes(matrix);
System.out.println(Arrays.deepToString(matrix));
PrintUtil.printDivider();
// 输入: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]]
matrix = new int[][] { { 0, 1, 2, 0 }, { 3, 4, 5, 2 }, { 1, 3, 1, 5 } };
System.out.println(Arrays.deepToString(matrix));
new Solution73_2().setZeroes(matrix);
System.out.println(Arrays.deepToString(matrix));
PrintUtil.printDivider();
}
}
class Solution73_1 {
public void setZeroes(int[][] matrix) {
HashSet<Integer> rows = new HashSet<>();
HashSet<Integer> cols = new HashSet<>();
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
if (matrix[row][col] == 0) {
rows.add(row);
cols.add(col);
}
}
}
for (int row : rows) {
for (int col = 0; col < matrix[0].length; col++) {
matrix[row][col] = 0;
}
}
for (int row = 0; row < matrix.length; row++) {
for (int col : cols) {
matrix[row][col] = 0;
}
}
}
}
class Solution73_2 {
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
boolean flagCol0 = false, flagRow0 = false;
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) {
flagCol0 = true;
}
}
for (int j = 0; j < n; j++) {
if (matrix[0][j] == 0) {
flagRow0 = true;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = matrix[0][j] = 0;
}
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (flagCol0) {
for (int i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
if (flagRow0) {
for (int j = 0; j < n; j++) {
matrix[0][j] = 0;
}
}
}
}