您将获得一个整数数组匹配,其中
matches[i] = [winneri, loseri]
表示在一场比赛中获胜者 (i) 击败了失败者 (i)。
返回大小为 2 的列表答案,其中:
answer[0]
是所有未输掉任何比赛的玩家的列表。
answer[1]
是所有输掉一场比赛的玩家的列表。
我的代码对于下面的很多测试用例都不起作用,但我无法理解为什么。
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
HashMap <Integer, Integer> trackMatches = new HashMap<>();
ArrayList<Integer> lostOnce = new ArrayList<>();
ArrayList<Integer> lostZero = new ArrayList<>();
for (int i = 0; i<matches.length; i++){
for (int j = 0; j<matches[i].length; j++){
if (trackMatches.containsKey(matches[i][j])){
if (j==1){
trackMatches.put(matches[i][j], trackMatches.get(matches[i][j])+1);
}
}
else{
if (j==0){
trackMatches.put(matches[i][j],0);
}
else if (j==1){
trackMatches.put(matches[i][j],1);
}
}
}
}
for (Map.Entry<Integer, Integer> entry: trackMatches.entrySet()){
int key = entry.getKey();
int value = entry.getValue();
if (value == 0){
lostZero.add(key);
}
else if(value == 1){
lostOnce.add(key);
}
}
List<List<Integer>> result = new ArrayList<>();
result.add(lostZero);
result.add(lostOnce);
return result;
}
}
您的代码输出正确的数字,但它们应该按排序顺序提供。因此,快速解决方法是将这两行添加到您的代码中:
Collections.sort(lostZero);
Collections.sort(lostOnce);