23-05-21 刷题
2225. 找出输掉零场或一场比赛的玩家 - 力扣(LeetCode)
思路:
- 这个太水了,直接使用HashMap和HashSet即可。
- 复杂度分析:
- 时间:O(nlogn). 遍历一遍,O(n),排序,最多有n个元素:O(n logn)。
- 空间:O(n)
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
Map<Integer, Integer> loseCount = new HashMap<>();
Set<Integer> winners = new HashSet<>();
for(int[] match : matches) {
int winner = match[0], loser = match[1];
winners.add(winner);
loseCount.put(loser, loseCount.getOrDefault(loser, 0) + 1);
}
List<List<Integer>> ans = new ArrayList<>();
//winners.removeIf(e -> loseCount.containsKey(e));
winners.removeAll(loseCount.keySet());
ans.add(new ArrayList<>(winners));
ans.add(new ArrayList<>());
for(Map.Entry<Integer, Integer> item : loseCount.entrySet()) {
if (item.getValue() == 1) { // only lose 1 match
ans.get(1).add(item.getKey());
}
}
Collections.sort(ans.get(0));
Collections.sort(ans.get(1));
return ans;
}
}
- 学习到的:求差集,这里使用了Set.removeIf()函数。也可以直接使用removeAll()方法。除此外,Set接口还有retainAll(another)方法,计算的是两个集合的交集。