Get Watched Videos by Your Friends
给一个list 表示朋友看的视频, 另一个list表示朋友之间的关系, 然后还有id, 就是你是谁, 还有level就是找几个friend level. 这个题就是普通的bfs, 注意一下查重.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Solution { public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) { boolean[] check = new boolean[watchedVideos.size()]; Arrays.fill(check, false); Queue<Integer> q = new LinkedList<>(); q.add(id); check[id] = true; List<Map.Entry<String, Integer>> tt = new ArrayList<>(); Map<String, Integer> map = new HashMap<>(); while (level > 0) { int size = q.size(); for (int i = 0; i < size; i++) { int ii = q.poll(); for (int iii : friends[ii]) { if (check[iii]) continue; check[iii] = true; q.add(iii); } } level--; } while (!q.isEmpty()) { List<String> list = watchedVideos.get(q.poll()); for (String s : list) { map.put(s, map.getOrDefault(s, 0) + 1); } } tt.addAll(map.entrySet()); Collections.sort(tt, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { if (o1.getValue() != o2.getValue()) return o1.getValue() - o2.getValue(); else return o1.getKey().compareTo(o2.getKey()); } }); List<String> res = new ArrayList<>(); for (Map.Entry<String, Integer> t : tt) res.add(t.getKey()); return res; } } |