Find Players With Zero or One Losses - Hashmap [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Hashmap
Use a hashmap to count the number of losses for each player.
In case a player hasn't lost any matches, we need to give it a count of 0 so that they are included in the hashmap.
Get the players with count 0 and the players with count 1.
Note: In JavaScript, the object keeps keys in ascending order, so we don't need to sort before returning.
Time Complexity: O(n)
Space Complexity: O(n)
var findWinners = function(matches) {
let lost = {};
for (let [winner, loser] of matches) {
lost[winner] = (lost[winner] || 0);
lost[loser] = (lost[loser] || 0) + 1;
}
let res = [[], []];
for (let player in lost) {
if (lost[player] === 0) res[0].push(+player);
else if (lost[player] === 1) res[1].push(+player);
}
return res;
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment