问题描述
在一款多人游戏中,每局比赛需要多个玩家参与。如果发现两名玩家至少一起玩过两局比赛,则可以认为这两名玩家互为队友。现在你有一份玩家(通过玩家ID标识)和比赛局次(通过比赛ID标识)的历史记录表,目标是帮助某位指定玩家找到所有符合条件的队友。
例如,已知以下比赛历史记录:
| 玩家ID | 游戏ID |
测试样例
样例1:
输入:
id = 1, num = 10, array = [[1,1], [1,2], [1,3], [2,1], [2,4], [3,2], [4,1], [4,2], [5,2], [5,3]]
输出:[4, 5]
样例2:
输入:
id = 2, num = 6, array = [[2,1], [2,3], [1,1], [1,2], [3,1], [4,3]]
输出:[]
样例3:
输入:
id = 3, num = 8, array = [[3,1], [3,2], [3,3], [4,1], [5,2], [6,3], [7,1], [7,2]]
输出:[7]
题目思路
- 初始化变量:创建一个
unordered_map用于存储每个玩家参与的游戏。 - 读取游戏记录:遍历
array数组,将每个玩家参与的游戏ID存储在对应的unordered_set中。 - 计算共同游戏次数:对于指定玩家参与的每个游戏,检查其他玩家是否也参与了该游戏,如果参与了,则增加共同游戏次数。
- 筛选队友:筛选出共同游戏次数大于等于2的玩家,并将它们添加到结果数组中。
- 排序:将结果数组按升序排序。
具体操作步骤
- 初始化变量:
- 创建一个
unordered_map用于存储每个玩家参与的游戏。
- 创建一个
- 读取游戏记录:
- 遍历
array数组,将每个玩家参与的游戏ID存储在对应的unordered_set中。
- 遍历
- 计算共同游戏次数:
- 对于指定玩家参与的每个游戏,检查其他玩家是否也参与了该游戏,如果参与了,则增加共同游戏次数。
- 筛选队友:
- 筛选出共同游戏次数大于等于2的玩家,并将它们添加到结果数组中。
- 排序:
- 将结果数组按升序排序。
代码实现
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
std::vector<int> solution(int id, int num, std::vector<std::vector<int>> array) {
// 存储每个玩家参与的游戏
std::unordered_map<int, std::unordered_set<int>> playerGames;
// 读取游戏记录并填充playerGames
for (const auto& record : array) {
int player = record[0];
int game = record[1];
playerGames[player].insert(game);
}
// 存储每个玩家与指定玩家的共同游戏次数
std::unordered_map<int, int> commonGamesCount;
// 计算指定玩家与其他玩家的共同游戏次数
for (int game : playerGames[id]) {
for (const auto& [player, games] : playerGames) {
if (player != id && games.count(game)) {
commonGamesCount[player]++;
}
}
}
// 筛选出共同游戏次数大于等于2的玩家
std::vector<int> teammates;
for (const auto& [player, count] : commonGamesCount) {
if (count >= 2) {
teammates.push_back(player);
}
}
// 按升序排序
std::sort(teammates.begin(), teammates.end());
return teammates;
}
int main() {
// Add your test cases here
std::vector<int> result = solution(1, 10, {{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 4}, {3, 2}, {4, 1}, {4, 2}, {5, 2}, {5, 3}});
std::cout << (result == std::vector<int>{4, 5}) << std::endl;
return 0;
}
知识总结:哈希表和排序的应用
哈希表:
- 哈希表是一种基于哈希函数的数据结构,用于存储键值对,具有快速的查找、插入和删除操作。