You are given an integer array matches
where matches[i] = [winneri, loseri]
indicates that the player winneri
defeated player loseri
in a match.
Return a list answer
of size 2
where:
answer[0]
is a list of all players that have not lost any matches.answer[1]
is a list of all players that have lost exactly one match.
The values in the two lists should be returned in increasing order.
Note:
- You should only consider the players that have played at least one match.
- The testcases will be generated such that no two matches will have the same outcome.
Example 1:
Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]] Output: [[1,2,10],[4,5,7,8]] Explanation: Players 1, 2, and 10 have not lost any matches. Players 4, 5, 7, and 8 each have lost one match. Players 3, 6, and 9 each have lost two matches. Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].
Example 2:
Input: matches = [[2,3],[1,3],[5,4],[6,4]] Output: [[1,2,5,6],[]] Explanation: Players 1, 2, 5, and 6 have not lost any matches. Players 3 and 4 each have lost two matches. Thus, answer[0] = [1,2,5,6] and answer[1] = [].
Constraints:
1 <= matches.length <= 105
matches[i].length == 2
1 <= winneri, loseri <= 105
winneri != loseri
- All
matches[i]
are unique.
找出输掉零场或一场比赛的玩家。
给你一个整数数组 matches 其中 matches[i] = [winneri, loseri] 表示在一场比赛中 winneri 击败了 loseri 。
返回一个长度为 2 的列表 answer :
answer[0] 是所有 没有 输掉任何比赛的玩家列表。
answer[1] 是所有恰好输掉 一场 比赛的玩家列表。
两个列表中的值都应该按 递增 顺序返回。注意:
只考虑那些参与 至少一场 比赛的玩家。
生成的测试用例保证 不存在 两场比赛结果 相同 。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-players-with-zero-or-one-losses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题不难,细心就行。思路是用哈希表存储所有出现过的玩家分别输了几场比赛,赢的场次不需要记录。注意返回之前需要把两个 sublist 分别排序。
时间O(nlogn)
空间O(n)
Java实现
1 class Solution { 2 public List<List<Integer>> findWinners(int[][] matches) { 3 HashMap<Integer, int[]> map = new HashMap<>(); 4 for (int[] m : matches) { 5 int winner = m[0]; 6 int loser = m[1]; 7 if (!map.containsKey(winner)) { 8 map.put(winner, new int[2]); 9 } 10 if (!map.containsKey(loser)) { 11 map.put(loser, new int[2]); 12 } 13 map.get(winner)[0]++; 14 map.get(loser)[1]++; 15 } 16 17 List<List<Integer>> res = new ArrayList<>(); 18 List<Integer> list1 = new ArrayList<>(); 19 List<Integer> list2 = new ArrayList<>(); 20 for (int key : map.keySet()) { 21 if (map.get(key)[1] == 0) { 22 list1.add(key); 23 } 24 if (map.get(key)[1] == 1) { 25 list2.add(key); 26 } 27 } 28 Collections.sort(list1); 29 Collections.sort(list2); 30 res.add(list1); 31 res.add(list2); 32 return res; 33 } 34 }
标签:map,2225,lost,Players,matches,Losses,int,answer,Find From: https://www.cnblogs.com/cnoodle/p/16934346.html