LeetCode 1311. 获取你好友已观看的视频(BFS+哈希map+vector排序)

1. 题目

有 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 广度优先搜索找到level层好友
  • 哈希map视频计数
  • map转vector排序,输出
class Solution {
    static bool cmp(const pair<string,int> &a,const pair<string,int> &b) 
	{	//vector自定义排序,类内需要加static,类外不用
		if(a.second == b.second)
			return a.first < b.first;
		return a.second < b.second;
	}
public:
    vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) {
    	queue<int> q;
    	int n = watchedVideos.size(), i, j, tp, size, lv = 0;
    	vector<bool> visited(n,false);
    	q.push(id);
    	visited[id] = true;
    	vector<int> lvfriend;
    	while(!q.empty())
    	{
    		size = q.size();
    		while(size--)
    		{
    			tp = q.front();
    			q.pop();
    			if(lv == level)
    				lvfriend.push_back(tp);
    			for(i = 0; i < friends[tp].size(); ++i)
    			{
    				if(!visited[friends[tp][i]])
    				{
    					q.push(friends[tp][i]);
    					visited[friends[tp][i]] = true;
    				}
    			}
    		}
    		lv++;
    		if(lv > level)
    			break;
    	}
    	unordered_map<string,int> m;
    	for(i = 0; i < lvfriend.size(); ++i)
    	{
    		for(j = 0; j < watchedVideos[lvfriend[i]].size(); ++j)
                m[watchedVideos[lvfriend[i]][j]]++;
    	}
        vector<pair<string,int>> v(m.begin(),m.end());
        sort(v.begin(),v.end(),cmp);
    	vector<string> ans(v.size());
    	for(i = 0; i < v.size(); ++i)
    		ans[i] = v[i].first;
    	return ans;
    }
};

240 ms 26.1 MB

原创文章 1053 获赞 4450 访问量 61万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/106086025