- 由于只考虑那些参与 至少一场 比赛的玩家,所以用一个 set 记录所有参赛的玩家。由于不确定有几个玩家,所以遍历 matches 找到其中最大值就相当于有几个玩家。最后用一个数组记录每个玩家失败的场次数。最终遍历该数组找到失败 0 或 1 次且参赛的玩家即可
-
public List<List<Integer>> findWinners(int[][] matches) { // 玩家数 int n = 0; // 参加比赛的玩家 Set<Integer> join = new HashSet<>(); for(int[] m : matches){ n = Math.max(Math.max(n, m[0]),m[1]); join.add(m[0]); join.add(m[1]); } // lose[i] = x: 玩家(i+1) 失败了 x 场 int[] lose = new int[n]; for(int[] m : matches){ lose[m[1] - 1]++; } List<List<Integer>> res = new ArrayList<>(); List<Integer> list0 = new ArrayList<>(); List<Integer> list1 = new ArrayList<>(); for(int i = 0; i < n; i++){ // 失败了 0 次且参与了 if(lose[i] == 0 && join.contains(i + 1))list0.add(i + 1); // 失败了 1 次且参与了 else if(lose[i] == 1 && join.contains(i + 1))list1.add(i + 1); } res.add(list0); res.add(list1); return res; }
- 他人解法:思路大致一样,不过用哈希表就能解决记录参与的玩家以及玩家失败次数这两点。
-
public List<List<Integer>> findWinners(int[][] matches) { Map<Integer, Integer> loser = new HashMap<>(); for(int[] m : matches){ if(!loser.containsKey(m[0]))loser.put(m[0], 0); loser.merge(m[1], 1, Integer::sum); } // 正好 ans[0] 对应输了 0 次的,ans[1] 对应输了 1 次的 List<List<Integer>> ans = List.of(new ArrayList<>(), new ArrayList<>()); for(Map.Entry<Integer, Integer> e : loser.entrySet()){ int loseCount = e.getValue(); if(loseCount < 2){ ans.get(loseCount).add(e.getKey()); } } Collections.sort(ans.get(0)); Collections.sort(ans.get(1)); return ans; }