-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode1337.java
More file actions
115 lines (106 loc) · 3.51 KB
/
LeetCode1337.java
File metadata and controls
115 lines (106 loc) · 3.51 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
107
108
109
110
111
112
113
114
115
import java.util.Arrays;
public class LeetCode1337 {
public static void main(String[] args) {
// 输入:mat =
// [[1,1,0,0,0],
// [1,1,1,1,0],
// [1,0,0,0,0],
// [1,1,0,0,0],
// [1,1,1,1,1]],
// k = 3
// 输出:[2,0,3]
System.out.println(Arrays.toString(new Solution1337().kWeakestRows(
new int[][] {
{ 1, 1, 0, 0, 0 },
{ 1, 1, 1, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 1, 1, 0, 0, 0 },
{ 1, 1, 1, 1, 1 }
},
3)));
// 输入:mat =
// [[1,0,0,0],
// [1,1,1,1],
// [1,0,0,0],
// [1,0,0,0]],
// k = 2
// 输出:[0,2]
System.out.println(Arrays.toString(new Solution1337().kWeakestRows(
new int[][] {
{ 1, 0, 0, 0 },
{ 1, 1, 1, 1 },
{ 1, 0, 0, 0 },
{ 1, 0, 0, 0 }
},
2)));
// 输入:mat = [[1,1,1,1,1,1],[1,1,1,1,1,1],[1,1,1,1,1,1]], k = 1;
// 输出:[0]
System.out.println(Arrays.toString(new Solution1337().kWeakestRows(
new int[][] {
{ 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1 }
},
1)));
// 输入:mat = [[1,0],[1,0],[1,0],[1,1]], k = 4;
// 输出:[0, 1, 2, 3]
System.out.println(Arrays.toString(new Solution1337().kWeakestRows(
new int[][] {
{ 1, 0 }, { 1, 0 }, { 1, 0 }, { 1, 1 }
},
4)));
// 输入:mat = [[1,0],[0,0],[1,0]], k = 2;
// 输出:[1, 0]
System.out.println(Arrays.toString(new Solution1337().kWeakestRows(
new int[][] {
{ 1, 0 }, { 0, 0 }, { 1, 0 }
},
2)));
// 输入:mat = [[1,1,0],[1,0,0],[1,0,0],[1,1,1],[1,1,0],[0,0,0]], k = 4;
// 输出:[5,1,2,0]
System.out.println(Arrays.toString(new Solution1337().kWeakestRows(
new int[][] {
{ 1, 1, 0 }, { 1, 0, 0 }, { 1, 0, 0 }, { 1, 1, 1 }, { 1, 1, 0 }, { 0, 0, 0 }
},
4)));
}
}
class Solution1337 {
public int[] kWeakestRows(int[][] mat, int k) {
boolean[] visited = new boolean[mat.length];
int[] result = new int[k];
int col = 0;
while (k > 0) {
for (int row = 0; row < mat.length; row++) {
if (visited[row]) {
continue;
}
if (mat[row][col] == 0) {
result[result.length - k] = row;
visited[row] = true;
k--;
if (k == 0) {
break;
}
}
}
col++;
if (col == mat[0].length) {
break;
}
}
if (k != 0) {
for (int row = 0; row < mat.length; row++) {
if (visited[row]) {
continue;
} else {
result[result.length - k] = row;
visited[row] = true;
k--;
if (k == 0) {
break;
}
}
}
}
return result;
}
}