在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. Format You can assume that no duplicate edges will appear in Example 1 : Input: Example 2 : Input: Note:
对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点。 格式 该图包含 你可以假设没有重复的边会出现在 示例 1: 输入: 示例 2: 输入: 说明:
1724 ms 1 class Solution { 2 func findMinHeightTrees(_ n: Int, _ edges: [[Int]]) -> [Int]{ 3 var graph = [Int : Set<Int>]() 4 for edge in edges { 5 if graph[edge[0]] == nil { 6 graph[edge[0]] = [edge[1]] 7 }else { 8 graph[edge[0]]!.insert(edge[1]) 9 } 10 if graph[edge[1]] == nil { 11 graph[edge[1]] = [edge[0]] 12 }else { 13 graph[edge[1]]!.insert(edge[0]) 14 } 15 16 } 17 while graph.count > 2 { 18 let list = graph.filter{$1.count == 1} 19 for dict in list { 20 graph[dict.value.first!]?.remove(dict.key) 21 graph[dict.key] = nil 22 } 23 } 24 25 let res = Array(graph.keys) 26 if res.isEmpty { 27 return [0] 28 } 29 return res 30 } 31 }
|
请发表评论