LeetCode Graph Valid Tree
2016-03-03 11:27
106 查看
原题链接在这里:https://leetcode.com/problems/graph-valid-tree/
题目:
Given
For example:
Given
Given
题解:
Union-Find, 与Number of Islands II相似.
若是数先判断 边的数量是不是 n-1.
然后判断有没有环,若是find(edge[0],edge[1])返回true 说明edge[0], edge[1]两个点之前就连在一起了.
Time Complexity: O(n*logn). Space: O(n).
AC Java:
题目:
Given
nnodes labeled from
0to
n - 1and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
For example:
Given
n = 5and
edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return
true.
Given
n = 5and
edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return
false.
题解:
Union-Find, 与Number of Islands II相似.
若是数先判断 边的数量是不是 n-1.
然后判断有没有环,若是find(edge[0],edge[1])返回true 说明edge[0], edge[1]两个点之前就连在一起了.
Time Complexity: O(n*logn). Space: O(n).
AC Java:
public class Solution { int [] parent; int [] size; public boolean validTree(int n, int[][] edges) { if(n < 0 || edges == null || edges.length != n-1){ return false; } parent = new int ; size = new int ; for(int i = 0; i<n ;i++){ parent[i] = i; size[i] = 1; } for(int [] edge : edges){ if(!find(edge[0], edge[1])){ union(edge[0], edge[1]); }else{ return false; } } return true; } private boolean find(int i, int j){ return root(i) == root(j); } private int root(int i){ while(i != parent[i]){ parent[i] = parent[parent[i]]; i = parent[i]; } return i; } private void union(int p, int q){ int i = root(p); int j = root(q); if(size[i] < size[j]){ parent[i] = j; size[j] += size[i]; }else{ parent[j] = i; size[i] += size[j]; } } }
相关文章推荐
- 超出TCP连接端口数限制(MaxUserPort)引起的服务器问题
- Android开发Can't create handler inside thread that has not called Looper.prepare()
- ABP总体介绍
- win7上使用eclipse阅读hadoop源码准备
- iOS- "unacceptable content-type: text/plain"等content-type bug解决方案
- dict中的“深拷贝”和“浅拷贝”
- Swift2.0(13)构造方法
- 虚函数 纯虚函数 抽象类
- 设计模式(7)——适配器模式(Adapter Pattern)
- 设计模式(6)——原型模式(Prototype Pattern)
- 使用poi来解析Excel的xls和xlsx
- 关于活动总结
- 81.You are currently located in Singapore and have connected to a remote database in Chicago.
- fastlane 使用中遇到的问题
- 如何使上层的div遮住的链接可以点击
- Android <shape />的使用
- TCP/IP、Http、Socket的区别
- 常用SQL语句汇总
- python读取mnist
- ThingWorx : 3、为Thing添加valueStream(web显示曲线做准备)