LeetCode 2225: Find Players With Zero or One Losses
Problem Description
Explanation
To solve this problem, we need to iterate through the matches and count the number of losses for each player. Players with zero losses will be added to the first list, and players with exactly one loss will be added to the second list. We can achieve this by using two HashMaps to keep track of the losses for each player. After iterating through all matches, we can check the HashMaps to form the final answer lists.
- Time Complexity: O(n), where n is the number of matches.
- Space Complexity: O(n), where n is the number of matches.
Solutions
import java.util.*;
class Solution {
public List<List<Integer>> findPlayers(int[][] matches) {
Map<Integer, Integer> losses = new HashMap<>();
Map<Integer, Integer> playerCount = new HashMap<>();
for (int[] match : matches) {
playerCount.put(match[0], playerCount.getOrDefault(match[0], 0) + 1);
playerCount.put(match[1], playerCount.getOrDefault(match[1], 0) + 1);
losses.put(match[1], losses.getOrDefault(match[1], 0) + 1);
}
List<Integer> zeroLoss = new ArrayList<>();
List<Integer> oneLoss = new ArrayList<>();
for (int player : playerCount.keySet()) {
if (losses.getOrDefault(player, 0) == 0) {
zeroLoss.add(player);
} else if (losses.get(player) == 1) {
oneLoss.add(player);
}
}
Collections.sort(zeroLoss);
Collections.sort(oneLoss);
return Arrays.asList(zeroLoss, oneLoss);
}
}
Loading editor...