---
# System prepended metadata

title: 1311. Get Watched Videos by Your Friends
tags: [Leetcode, BFS, Medium]

---

# 1311. Get Watched Videos by Your Friends
###### tags: `Leetcode` `BFS` `Medium`
Link: https://leetcode.com/problems/get-watched-videos-by-your-friends/
## 思路 $O(NlogN)$ $O(N)$
先找到```level```那一层的friend
然后把他们的videos出现的freq统计出来最后得出答案
## Code
```java=
class Solution {
    public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) {
        //find friends
        boolean[] visited = new boolean[friends.length];
        Queue<Integer> q = new LinkedList<>();
        visited[id]=true;
        q.add(id);
        int step = 0;
        while(!q.isEmpty()){
            int size = q.size();
            for(int i=0; i<size; i++){
                int friend = q.poll();
                for(int f:friends[friend]){
                    if(!visited[f]){
                        visited[f] = true;
                        q.add(f);
                    }
                }
            }
            if(++step == level) break;
        }
        
        Map<String, Integer> freq = new HashMap<>();
        for(int friend:q){
            for(String video:watchedVideos.get(friend)){
                freq.put(video, freq.getOrDefault(video,0)+1);
            }
        }
        List<String> ans = new ArrayList<>();
        for(String key:freq.keySet()) ans.add(key);
        Collections.sort(ans, (a,b)->freq.get(a)==freq.get(b)?a.compareTo(b):freq.get(a)-freq.get(b));
        return ans;
    }
}
```