/**
* @param {number[][]} mat
* @param {number} k
* @return {number[]}
*/
var kWeakestRows = function(mat, k) {
const m = mat.length;
const indexWithCnt = mat.map((arr, i) => {
let count = 0;
for (const n of arr)
if(n)
count++;
return [i, count];
});
return indexWithCnt
.sort((a, b) => a[1] - b[1])
.slice(0, k)
.map(el => el[0]);
};
Time: O(mn + nlogn)
Space: O(m + k)
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
int[] sumArr = new int[mat.length];
for(int i=0; i<mat.length; i++){
int sum=0;
for(int j=0; j<mat[0].length; j++){
if(mat[i][j]==1){
sum++;
}
}
sumArr[i]=sum*1000+i;
}
Arrays.sort(sumArr);
int[] res = new int[k];
for(int i=0; i<k; i++){
res[i]= sumArr[i]%1000;
}
return res;
}
}
Time: O(MN + NlogN)
Space: O(N)