Title description:
Give you a matrix mat of size m * n. The matrix consists of a number of soldiers and civilians, denoted by 1 and 0 respectively. Please return the index of the k rows with the weakest combat effectiveness in the matrix, sorted from weakest to strongest.
If the number of soldiers in the i-th row is less than that in the j-th row, or the number of soldiers in the two rows is the same but i is less than j, then we think that the combat power of the i-th row is weaker than that of the j-th row. Soldiers are always at the top of the line, which means that 1 always appears before 0.
Hint:
m == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j] is either 0 or 1
Example 1:
Input: 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
Output: [2,0,3]
Explanation:
The number of soldiers in each line:
line 0 -> 2
line 1 -> 4
Row 2 -> 1
Row 3 -> 2
Row 4 -> 5
Sort these rows from weakest to strongest to get [2,0,3,1,4]
Example 2:
Input: mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
Output: [0,2]
Explanation:
Number of soldiers in each line:
Line 0 ->
Line 1 ->
Line 4 ->
Line 3 -> 1
Sort these lines from weakest to strongest. [0,2,3,1]
code show as below:
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
int m = mat.length;
int n = mat[0].length;
int sum = 0;
int[][] num = new int[m][2];
int[] arr = new int[k];
for (int i = 0; i < m; i++) {
sum = 0;
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
sum++;
}
}
num[i][0] = i;
num[i][1] = sum;
}
Arrays.sort(num, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] == o2[1] ? o1[0] - o2[0] : o1[1] - o2[1];
}
});
for (int i = 0; i < k; i++) {
arr[i] = num[i][0];
}
return arr;
}
}
Results of the: