leetcode -- Minimum Height Trees -- 关于graph的,重点
2015-12-10 22:29
246 查看
https://leetcode.com/problems/minimum-height-trees/
有trick
对graph不熟悉。再看几遍。
参考http://bookshadow.com/weblog/2015/11/26/leetcode-minimum-height-trees/
基本思路是“逐层删去叶子节点,直到剩下根节点为止”
有点类似于拓扑排序
最终剩下的节点个数可能为1或者2
时间复杂度:O(n),其中n为顶点的个数。
记住这些结论以及这样的code怎么写就行了。就跟拓扑排序一样,逐次去掉leaf node
有trick
对graph不熟悉。再看几遍。
参考http://bookshadow.com/weblog/2015/11/26/leetcode-minimum-height-trees/
基本思路是“逐层删去叶子节点,直到剩下根节点为止”
有点类似于拓扑排序
最终剩下的节点个数可能为1或者2
时间复杂度:O(n),其中n为顶点的个数。
记住这些结论以及这样的code怎么写就行了。就跟拓扑排序一样,逐次去掉leaf node
class Solution(object): def findMinHeightTrees(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[int] """ children = collections.defaultdict(set) for s, t in edges:#记录edge children[s].add(t) children[t].add(s) vertices = set(children.keys()) while len(vertices) > 2: leaves = [x for x in children if len(children[x]) == 1] for x in leaves: for y in children[x]: children[y].remove(x) del children[x] vertices.remove(x) return list(vertices) if n != 1 else [0]
相关文章推荐
- HDU 2082 找单词
- 市场调查与分析概述2
- System.currentTimeMillis()与SystemClock.uptimeMillis()
- python学习日记_第三天(ex6~8)
- UIScrollView, UIPageControl 的详细使用
- [笔记] 大型网站技术架构——核心原理与案例分析 [二]
- Mac OS apache php配置
- 转载几篇别人写的皮肤类控件的技术文章
- Mac OS apache php配置
- 零崎的悠哉日常Ⅱ
- 投影机使用维护保养小常识
- CodeForces 377C/378E Captains Mode 状态压缩动态规划
- 欢迎使用CSDN-markdown编辑器
- 母盘制作全步骤
- 使用QGIS将文本坐标转换为矢量文件
- 四大组件之内容提供者
- 蛇形矩阵
- string与char*的转换方法
- warning: rpmts_HdrFromFdno: Header V4 DSA/SHA1 Signature, key ID 7fac5991: NOKEY
- Leaving on a jet plane