问题:
朋友看视频问题。
给定一个朋友关系网,
friends[i]表示 i 的朋友们。
watchedVideos[i]表示 i 所看的视频。
level表示朋友层,1:代表i的朋友,2:代表i的朋友的朋友。
求给定人 i 的朋友层level,所看过的所有视频。(按照视频被看的人数从少到多排序)
Example 1:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
Output: ["B","C"]
Explanation:
You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
Person with id = 1 -> watchedVideos = ["C"]
Person with id = 2 -> watchedVideos = ["B","C"]
The frequencies of watchedVideos by your friends are:
B -> 1
C -> 2
Example 2:
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["D"]
Explanation:
You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
Constraints:
n == watchedVideos.length == friends.length
2 <= n <= 100
1 <= watchedVideos[i].length <= 100
1 <= watchedVideos[i][j].length <= 8
0 <= friends[i].length < n
0 <= friends[i][j] < n
0 <= id < n
1 <= level < n
if friends[i] contains j, then friends[j] contains i
example 1:
example 2:
解法:BFS
状态:当前人 id
visited:保存遍历过的人 id
level按照queue遍历层数进行递减。
当level递减到0,开始记录该层人所看过的视频。
存入unordered_map中,key:视频,value:看过的人数
每层遍历完,如果level==0,退出遍历。
将结果存入set中,进行排序(first:看过的人数。second:视频)
再将set转存入结果vector<string> 即为已排过序的结果。
代码参考:
class Solution {
public:
vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) {
queue<int> q;
unordered_set<int> visited;
unordered_map<string,int> res_map;
vector<string> res;
q.push(id);
visited.insert(id);
while(!q.empty()) {
int sz = q.size();
for(int i=0; i<sz; i++) {
int cur = q.front();
q.pop();
//cout<<"pop:"<<cur<<" level:"<<level<<endl;
if(level==0) {
for(auto vd:watchedVideos[cur])
res_map[vd]++;
} else {
for(auto frd:friends[cur]) {
if(visited.insert(frd).second) {
q.push(frd);
}
}
}
}
if(level==0) break;
level--;
}
set<pair<int,string>> res_set;
for(auto rm:res_map) {
res_set.insert({rm.second,rm.first});
}
for(auto rs:res_set) {
res.push_back(rs.second);
}
return res;
}
};