目录
题目描述
给你一个整数数组 matches
其中 matches[i] = [winneri, loseri]
表示在一场比赛中 winneri
击败了 loseri
。
返回一个长度为 2 的列表 answer
:
answer[0]
是所有 没有 输掉任何比赛的玩家列表。answer[1]
是所有恰好输掉 一场 比赛的玩家列表。
两个列表中的值都应该按 递增 顺序返回。
注意:
- 只考虑那些参与 至少一场 比赛的玩家。
- 生成的测试用例保证 不存在 两场比赛结果 相同 。
解题思路
根据题目的描述,结果需要返回的数据是全胜的玩家以及只输了一场比赛的玩家,所以可以记录每个玩家的失败次数,根据失败次数来构建返回的数据。
因此可以选用HashMap来记录数据,通过遍历数组, matches[0]为胜者,
matches[1]为败者,将胜者的值设为0,败者则将值+1。
这里要注意的时,如果map中含有该胜者的数据的话则需要忽略本次的胜者,因为它已经在map中,
最后通过遍历map中的数据,根据失败次数选择加入全胜集合、失败一场的集合或者不加入。
代码
public List<List<Integer>> findWinners2(int[][] matches) {
//初始化返回结果
List<List<Integer>> res = new ArrayList<>();
//创建全胜以及失败一场的玩家集合
List<Integer> winner = new ArrayList<>();
List<Integer> loser = new ArrayList<>();
//将两个集合加入返回结果
Collections.addAll(res, winner, loser);
HashMap<Integer, Integer> map = new HashMap<>();
//遍历数组
for (int[] arr : matches) {
//胜者
int num1 = arr[0];
//败者
int num2 = arr[1];
//这里表示的是,如果map中不存在num1这个数据,才会push
map.putIfAbsent(num1, 0);
//这里表示的时,push num2时,如果不存在,则值为1,如果存在则在原先的值上+1
map.put(num2, map.getOrDefault(num2, 0) + 1);
}
//遍历map
for (Integer keySet : map.keySet()) {
//如果没失败过,加入全胜集合
if (map.get(keySet) == 0) {
winner.add(keySet);
//失败过一次加入另一个集合
} else if (map.get(keySet) == 1) {
loser.add(keySet);
}
}
//对两个集合进行排序
Collections.sort(winner);
Collections.sort(loser);
return res;
}