leetcode1311. 获取你好友已观看的视频

有 n 个人,每个人都有一个  0 到 n-1 的唯一 id 。

给你数组 watchedVideos  和 friends ,其中 watchedVideos[i]  和 friends[i] 分别表示 id = i 的人观看过的视频列表和他的好友列表。

Level 1 的视频包含所有你好友观看过的视频,level 2 的视频包含所有你好友的好友观看过的视频,以此类推。一般的,Level 为 k 的视频包含所有从你出发,最短距离为 k 的好友观看过的视频。

给定你的 id  和一个 level 值,请你找出所有指定 level 的视频,并将它们按观看频率升序返回。如果有频率相同的视频,请将它们按名字字典序从小到大排列。

 

示例 1:

输入:watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
输出:["B","C"] 
解释:
你的 id 为 0 ,你的朋友包括:
id 为 1 -> watchedVideos = ["C"] 
id 为 2 -> watchedVideos = ["B","C"] 
你朋友观看过视频的频率为:
B -> 1 
C -> 2
示例 2:

输入:watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
输出:["D"]
解释:
你的 id 为 0 ,你朋友的朋友只有一个人,他的 id 为 3 。
 

提示:

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
如果 friends[i] 包含 j ,那么 friends[j] 包含 i

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/get-watched-videos-by-your-friends
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

class Solution {
public:
    vector<string> watchedVideosByFriends(vector<vector<string>>& w, vector<vector<int>>& f, int id, int level) {
        int n = w.size();
        vector<string> res;
        bool st[n + 1] = {false};
        st[id] = true;
        queue<int> q;
        for(int i : f[id])
            q.push(i);
        
        unordered_map<string, int> mp;
        while(q.size() && level--)
        {
            int len = q.size();
            mp.clear();
            
            while(len--)
            {
                int t = q.front(); q.pop();
                if(st[t]) continue;
                st[t] = true;
                
                for(string str : w[t]) mp[str]++;
                for(int i : f[t])
                    if(!st[i])
                        q.push(i);
            }
        }
        vector<pair<int, string>> pii;
        for(auto i : mp) pii.push_back({i.second, i.first});
        sort(pii.begin(), pii.end());
        
        for(auto i : pii) res.push_back(i.second);
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章