题目
给你一个整数数组 matches 其中 matches[i] = [winneri, loseri] 表示在一场比赛中 winneri 击败了 loseri 。
返回一个长度为 2 的列表 **answer :
answer[0]是所有 没有 输掉任何比赛的玩家列表。answer[1]是所有恰好输掉 一场 比赛的玩家列表。
两个列表中的值都应该按 递增 顺序返回。
注意:
- 只考虑那些参与 至少一场 比赛的玩家。
- 生成的测试用例保证 不存在 两场比赛结果 相同 。
思路
题目要求返回输了0场和1场的玩家.
我们需要一个能够存储玩家和对应所输场次的集合.所以使用 Map 来存储对应关系,(也可以使用数组存储)
存储后将所输场次为 0 和 1 的分别存储到 List 集合中,并且排序即可.
代码
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
Map<Integer, Integer> map = new HashMap<>();
for (int[] match : matches) {
int winner = match[0];
int loser = match[1];
map.put(winner, map.getOrDefault(winner,0));
map.put(loser, map.getOrDefault(loser, 0) + 1);
}
List<Integer> winList = new ArrayList<>();
List<Integer> loseOne = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
Integer value = entry.getValue();
Integer key = entry.getKey();
if (value == 0) {
winList.add(key);
} else if (value == 1) {
loseOne.add(key);
}
}
winList.sort(Comparator.naturalOrder());
loseOne.sort(Comparator.naturalOrder());
return List.of(winList, loseOne);
}
}