2225.找出输掉零场或一场比赛的玩家

【LetMeFly】2225.找出输掉零场或一场比赛的玩家:哈希表计数

力扣题目链接:https://leetcode.cn/problems/find-players-with-zero-or-one-losses/

给你一个整数数组 matches 其中 matches[i] = [winneri, loseri] 表示在一场比赛中 winneri 击败了 loseri

返回一个长度为 2 的列表 answer

  • answer[0] 是所有 没有 输掉任何比赛的玩家列表。
  • answer[1] 是所有恰好输掉 一场 比赛的玩家列表。

两个列表中的值都应该按 递增 顺序返回。

注意:

  • 只考虑那些参与 至少一场 比赛的玩家。
  • 生成的测试用例保证 不存在 两场比赛结果 相同

 

示例 1:

输入:matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
输出:[[1,2,10],[4,5,7,8]]
解释:
玩家 1、2 和 10 都没有输掉任何比赛。
玩家 4、5、7 和 8 每个都输掉一场比赛。
玩家 3、6 和 9 每个都输掉两场比赛。
因此,answer[0] = [1,2,10] 和 answer[1] = [4,5,7,8] 。

示例 2:

输入:matches = [[2,3],[1,3],[5,4],[6,4]]
输出:[[1,2,5,6],[]]
解释:
玩家 1、2、5 和 6 都没有输掉任何比赛。
玩家 3 和 4 每个都输掉两场比赛。
因此,answer[0] = [1,2,5,6] 和 answer[1] = [] 。

 

提示:

  • 1 <= matches.length <= 105
  • matches[i].length == 2
  • 1 <= winneri, loseri <= 105
  • winneri != loseri
  • 所有 matches[i] 互不相同

解题方法:哈希表

使用一个哈希表,记录每个玩家的输的次数。

遍历所有比赛数组:

  • winner的输次数加0;
  • loser的输次数加1。

最后遍历哈希表,将总输次数为0和1的玩家分别放入答案数组的对应位置,最后再分别排个序。

为什么winner还要“加0”?因为不“加0”的话可能导致哈希表中从来没有出现过这个人,最后就统计不到“东方不败”了。

  • 时间复杂度$O(len(matches)\times \log len(matches))$
  • 空间复杂度$O(len(matches))$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<vector<int>> findWinners(vector<vector<int>>& matches) {
vector<vector<int>> ans(2);
unordered_map<int, int> cnt;
for (vector<int>& match : matches) {
cnt[match[0]] += 0;
cnt[match[1]]++;
}
for (auto&& [id, times] : cnt) {
if (times == 0) {
ans[0].push_back(id);
}
else if (times == 1) {
ans[1].push_back(id);
}
}
sort(ans[0].begin(), ans[0].end());
sort(ans[1].begin(), ans[1].end());
return ans;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# from typing import List
# from collections import defaultdict

class Solution:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
ans = [[], []]
cnt = defaultdict(int)
for winner, loser in matches:
cnt[winner] += 0
cnt[loser] += 1
for id_, times in cnt.items():
if times == 0:
ans[0].append(id_)
elif times == 1:
ans[1].append(id_)
ans[0].sort()
ans[1].sort()
return ans

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/139128938


2225.找出输掉零场或一场比赛的玩家
https://blog.letmefly.xyz/2024/05/22/LeetCode 2225.找出输掉零场或一场比赛的玩家/
作者
Tisfy
发布于
2024年5月22日
许可协议