Created
March 27, 2022 10:09
-
-
Save esase/7d6d7d7eb7a15aae9573e3edc488333d to your computer and use it in GitHub Desktop.
The-k-weakest-rows-in-a-matrix [https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var kWeakestRows = function(mat, k) { | |
const soldierList = []; | |
for(let i = 0; i < mat.length; i++) { | |
let soldiers = 0; | |
for (j = 0; j < mat[i].length; j++) { | |
if (mat[i][j]) { | |
soldiers++; | |
} | |
} | |
soldierList.push({ | |
index: i, | |
soldiers | |
}); | |
} | |
soldierList.sort((a, b) => { | |
if (a.soldiers === b.soldiers) { | |
return a.index - b.index; | |
} | |
return a.soldiers > b.soldiers ? 1 : -1; | |
}); | |
const result = []; | |
for (let i = 0; i < k; i++) { | |
result.push(soldierList[i]['index']); | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment