# 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; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up