👬 获取你好友已观看的视频
📝 题目描述
有n
个人,每个人都有一个0
到n-1
的唯一id。
给你数组watchedVideos
和friends
,其中watchedVideos[i]
和friends[i]
分别表示id = i
的人观看过的视频列表和他的好友列表。
Level 1的视频包含所有你好友观看过的视频,level 2的视频包含所有你好友的好友观看过的视频,以此类推。一般的,Level 为k的视频包含所有从你出发,最短距离为k的好友观看过的视频。
给定你的id
和一个level
值,请你找出所有指定level
的视频,并将它们按观看频率升序返回。如果有频率相同的视频,请将它们按字母顺序从小到大排列。
📋 代码模板
java
class Solution {
public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) {
}
}
typescript
function watchedVideosByFriends(watchedVideos: string[][], friends: number[][], id: number, level: number): string[] {
}
💡 提示
- 如果
包含 ,那么 包含
🚀 示例
🖊️ 题解
可惜没有如果
java
class Solution {
public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends,
int id, int level) {
int n = friends.length;
boolean[] visited = new boolean[n];
Queue<Integer> queue = new LinkedList<>();
queue.offer(id);
visited[id] = true;
while (!queue.isEmpty() && level > 0) {
int size = queue.size();
while (size > 0) {
int i = queue.poll();
for (int friend : friends[i]) {
if (!visited[friend]) {
queue.offer(friend);
visited[friend] = true;
}
}
size--;
}
level--;
}
List<String> videos = new ArrayList<>();
Map<String, Integer> frequency = new HashMap<>();
while (!queue.isEmpty()) {
for (String video : watchedVideos.get(queue.poll())) {
boolean isContains = frequency.containsKey(video);
frequency.put(video, (isContains ? frequency.get(video) : 0) + 1);
if (!isContains) {
videos.add(video);
}
}
}
videos.sort(Comparator.comparing((String video) -> frequency.get(video))
.thenComparing(Comparator.naturalOrder()));
return videos;
}
}
typescript
function watchedVideosByFriends(watchedVideos: string[][], friends: number[][]
, id: number, level: number): string[] {
const n = friends.length;
const visited: boolean[] = Array(n).fill(false);
const queue: number[] = [];
queue.push(id);
visited[id] = true;
while (queue.length > 0 && level > 0) {
let size = queue.length;
while (size > 0) {
const i: number = queue.shift()!;
for (const friend of friends[i]) {
if (!visited[friend]) {
queue.push(friend);
visited[friend] = true;
}
}
size--;
}
level--;
}
const frequency = new Map<string, number>();
const videos: string[] = [];
while (queue.length > 0) {
for (const video of watchedVideos[queue.shift()!]) {
const isContains = frequency.has(video);
frequency.set(video, (isContains ? frequency.get(video)! : 0) + 1);
if (!isContains) {
videos.push(video);
}
}
}
videos.sort((v1, v2) => {
const cnt1 = frequency.get(v1)!, cnt2 = frequency.get(v2)!
if (cnt1 != cnt2) {
return cnt1 - cnt2;
}
if (v1 != v2) {
return v1 > v2 ? 1 : -1;
}
return 0;
})
return videos;
}