本文共 2167 字,大约阅读时间需要 7 分钟。
要解决这个问题,我们需要找到指定层数的视频,并按观看频率和字母顺序排列。以下是详细的解决方案:
问题分析:我们需要找到从给定id出发,最短距离为指定level的好友,并统计他们观看的视频频率。使用广度优先搜索(BFS)可以逐层扩展好友网络,找到指定层数的好友。
数据结构选择:
步骤:
import java.util.*;public class Solution { public ListwatchedVideosByFriends(List
> watchedVideos, int[][] friends, int id, int level) { // 使用队列来进行广度优先搜索 Queue queue = new LinkedList<>(); Set visited = new HashSet<>(); // 初始化队列 queue.add(id); visited.add(id); List result = new ArrayList<>(); // 处理level=0的情况,即当前用户自己 if (level == 0) { for (List videos : watchedVideos) { for (String video : videos) { result.add(video); } } return result; } // 进行广度优先搜索,找到指定level的好友 while (true) { if (queue.isEmpty()) { break; } int currentLevelSize = queue.size(); // 处理当前层级的所有节点 for (int i = 0; i < currentLevelSize; i++) { int currentId = queue.poll(); // 遍历当前id的所有好友 for (int friendId : friends[currentId]) { if (!visited.contains(friendId)) { visited.add(friendId); queue.add(friendId); } } } // 当前层级处理完毕,level加一 if (visited.size() == level) { break; } } // 收集指定层级的好友,并统计他们看过的视频 Map videoCount = new HashMap<>(); while (!queue.isEmpty()) { int currentId = queue.poll(); List videos = watchedVideos.get(currentId); for (String video : videos) { videoCount.put(video, videoCount.getOrDefault(video, 0) + 1); } } // 使用优先队列对视频进行排序 PriorityQueue priorityQueue = new PriorityQueue<>( (a, b) -> { // 先按频率降序排列,频率相同则按字母升序排列 if (videoCount.get(a).equals(videoCount.get(b))) { return a.compareTo(b); } else { return Integer.compare(videoCount.get(b), videoCount.get(a)); } }); for (String video : videoCount.keySet()) { priorityQueue.add(video); } // 构建结果列表 while (!priorityQueue.isEmpty()) { result.add(priorityQueue.poll()); } return result; }}
这个方法通过BFS逐层扩展好友网络,确保找到所有指定层数的好友,并高效统计和排序视频,解决了问题。
转载地址:http://spgr.baihongyu.com/