描述
给你一个整数数组 matches 其中 matches[i] = [winneri, loseri] 表示在一场比赛中 winneri 击败了 loseri 。
返回一个长度为 2 的列表 answer :
answer[0] 是所有 没有 输掉任何比赛的玩家列表。
answer[1] 是所有恰好输掉 一场 比赛的玩家列表。
两个列表中的值都应该按 递增 顺序返回。
注意:
只考虑那些参与 至少一场 比赛的玩家。
生成的测试用例保证 不存在 两场比赛结果 相同 。
分析
遍历数组,用map统计每个选手输掉比赛的情况,map的键值对是用户名与输掉的次数。输了累加1,没输且map中不存在该用户则新增用户且输掉次数为0。
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
Map<Integer,Integer> lose = new HashMap<>();
for(int[] li : matches){
if(!lose.containsKey(li[0])){
lose.put(li[0],0);
}
if(!lose.containsKey(li[1])){
lose.put(li[1],0);
}
lose.put(li[1],lose.get(li[1])+1);
}
List<Integer> zero = new ArrayList<>();
List<Integer> one = new ArrayList<>();
for(int num : lose.keySet()){
int times = lose.get(num);
if(times == 0){
zero.add(num);
}
if(times == 1){
one.add(num);
}
}
List<List<Integer>> ans = new ArrayList<>();
Collections.sort(zero);
Collections.sort(one);
ans.add(zero);
ans.add(one);
return ans;
}
}