在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ There are Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path equal to k with you. Given your
Example 1: Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 Output: ["B","C"] Explanation: You have id = 0 (green color in the figure) and your friends are (yellow color in the figure): Person with id = 1 -> watchedVideos = ["C"] Person with id = 2 -> watchedVideos = ["B","C"] The frequencies of watchedVideos by your friends are: B -> 1 C -> 2 Example 2: Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2 Output: ["D"] Explanation: You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).
Constraints:
有 给你数组 Level 1 的视频包含所有你好友观看过的视频,level 2 的视频包含所有你好友的好友观看过的视频,以此类推。一般的,Level 为 k 的视频包含所有从你出发,最短距离为 k 的好友观看过的视频。 给定你的
示例 1: 输入:watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1 输出:["B","C"] 解释: 你的 id 为 0 ,你的朋友包括: id 为 1 -> watchedVideos = ["C"] id 为 2 -> watchedVideos = ["B","C"] 你朋友观看过视频的频率为: B -> 1 C -> 2 示例 2: 输入:watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2 输出:["D"] 解释: 你的 id 为 0 ,你朋友的朋友只有一个人,他的 id 为 3 。
提示:
Runtime: 588 ms
Memory Usage: 23.6 MB
1 class Solution { 2 func watchedVideosByFriends(_ watchedVideos: [[String]], _ friends: [[Int]], _ id: Int, _ level: Int) -> [String] { 3 var videosCounter = [String:Int]() 4 var queue: [Int] = [id] 5 var visited = Array<Bool>(repeating: false, count: friends.count) 6 visited[id] = true 7 var depth = 0 8 while !queue.isEmpty && depth <= level{ 9 var nextLevel = [Int]() 10 queue.forEach { 11 if depth == level { 12 watchedVideos[$0].forEach { videosCounter.updateValue((videosCounter[$0] ?? 0) + 1, forKey: $0)} 13 } else { 14 friends[$0].forEach { 15 if !visited[$0] { 16 visited[$0] = true 17 nextLevel.append($0) 18 } 19 } 20 } 21 } 22 queue = nextLevel 23 depth += 1 24 } 25 let sortedVideoCounter = videosCounter.sorted { (argv1, argv2) -> Bool in 26 if argv1.value == argv2.value { 27 return argv1.key < argv2.key 28 } 29 return argv1.value < argv2.value 30 } 31 return sortedVideoCounter.map {$0.key} 32 } 33 }
|
请发表评论