[LeetCode] 2225. Find Players With Zero or One Losses
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] = [winner, loser] 表示在一场比赛中 winner 击败了 loser 。返回一个长度为 2 的列表 answer :
answer[0] 是所有 没有 输掉任何比赛的玩家列表。
answer[1] 是所有恰好输掉 一场 比赛的玩家列表。
两个列表中的值都应该按 递增 顺序返回。注意:
只考虑那些参与 至少一场 比赛的玩家。
生成的测试用例保证 不存在 两场比赛结果 相同 。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-players-with-zero-or-one-losses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这道题不难,细心就行。思路是用哈希表存储所有出现过的玩家分别输了几场比赛,赢的场次不需要记录。注意返回之前需要把两个 sublist 分别排序。
复杂度
时间O(nlogn)
空间O(n)
代码
Java实现
class Solution {
public List<List<Integer>> findWinners(int[][] matches) {
HashMap<Integer, int[]> map = new HashMap<>();
for (int[] match : matches) {
int winner = match[0];
int loser = match[1];
if (!map.containsKey(winner)) {
map.put(winner, new int[2]);
}
map.get(winner)[0]++;
if (!map.containsKey(loser)) {
map.put(loser, new int[2]);
}
map.get(loser)[1]++;
}
List<List<Integer>> res = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
for (int player : map.keySet()) {
if (map.get(player)[1] == 0) {
list1.add(player);
}
if (map.get(player)[1] == 1) {
list2.add(player);
}
}
Collections.sort(list1);
Collections.sort(list2);
res.add(list1);
res.add(list2);
return res;
}
}