20240114-寻找零损失或一损失的玩家

题目要求

给定一个整数数组 matches,其中 matches[i] = [winneri, Loseri] 表示玩家 Winneri 在一场比赛中击败了玩家 Loseri。

返回大小为 2 的列表答案,其中:

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

两个列表中的值应按升序返回。

您应该只考虑至少参加过一场比赛的球员。

生成的测试用例不会有任何两个匹配具有相同的结果。

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] = [].

思路

先把参与比赛的队伍的list得到,然后用哈希表统计输的次数,如果哈希表中的队伍没有出现在全部list中则是全胜的。然后再统计只输一场的即可。

代码

class Solution {
public:
    vector<vector<int>> findWinners(vector<vector<int>>& matches) {
        vector<vector<int>> res(2);
        // 统计不重复的队伍,用到set
        set<int> teams;
        map<int, int> losses;
        for (auto& match : matches) {
            teams.insert(match[0]);
            teams.insert(match[1]);
            losses[match[1]]++;
        }
        
        for (int team : teams) {
            if (losses.find(team) == losses.end()) {
                res[0].push_back(team);
            } else if (losses[team] == 1) {
                res[1].push_back(team);
            }
        }

        sort(res[0].begin(), res[0].end());
        sort(res[1].begin(), res[1].end());
        return res;
    }
};

时间复杂度:

遍历每场比赛的主循环的时间复杂度为 O(N),其中 N 为比赛场次。
查找无失利或正好有一场失利的球队的循环复杂度为 O(T),其中 T 是唯一球队的数量。
对于 res 中的两个子向量,排序功能的复杂度均为 O(T log T)。
总的来说,时间复杂度约为 O(N + T log T)。


空间复杂度:

空间复杂度主要取决于存储团队和失利队伍映射所需的空间。
Map和Set共需要 O(T) 个空间,其中 T 是唯一球队的数量。
结果向量需要额外的空间,但不会超过 O(T)。
因此,总的空间复杂度为 O(T)。

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值