Give you a m * n
matrix of size mat
, the matrix is composed of a number of soldiers and civilians, represented by 1 and 0 respectively.
Please return k
the index of the row with the weakest combat effectiveness in the matrix , sorted from weakest to strongest.
If the first i the number of soldiers line is less than the first j line, two lines or the same number of soldiers but i is less than j , then we think the first i fighting than the first row j weak line.
Soldiers are always at the top of the line, which means that 1 always appears before 0.
Example 1:
输入: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]
解释:
每行中的军人数目:
行 0 -> 2
行 1 -> 4
行 2 -> 1
行 3 -> 2
行 4 -> 5
从最弱到最强对这些行排序后得到 [2,0,3,1,4]
Example 2:
输入:mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
输出:[0,2]
解释:
每行中的军人数目:
行 0 -> 1
行 1 -> 4
行 2 -> 1
行 3 -> 1
从最弱到最强对这些行排序后得到 [0,2,3,1]
prompt:
m == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j]
Either 0 or 1
import java.util.Arrays;
public class Solution1337 {
public int[] kWeakestRows(int[][] mat, int k) {
int[] out = new int[k];
int[] sum = new int[mat.length];
int count = 0;
for (int i = 0; i < mat.length; i++) {
count = 0;
for (int j = 0; j < mat[0].length; j++) {
if (mat[i][j] == 1) {
count++;
}
}
sum[i] = count;
}
// System.out.println(Arrays.toString(sum));
int[] sort = sum.clone();
Arrays.sort(sort);
// System.out.println(Arrays.toString(sort));
for (int i = 0; i < k; i++) {
for (int j = 0; j < sum.length; j++) {
if (sort[i] == sum[j]) {
sum[j] = -1;
out[i] = j;
break;
}
}
}
return out;
}
public static void main(String[] args) {
Solution1337 sol = new Solution1337();
int[][] 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 } };
int k = 3;
System.out.println(Arrays.toString(sol.kWeakestRows(mat, k)));
}
}