首页 > 其他 > 详细

LeetCode Graph Valid Tree

时间:2016-03-03 12:59:54      阅读:259      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/graph-valid-tree/

题目:

Given n nodes labeled from 0 to n - 1 and 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 = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.

Given n = 5 and 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:

 1 public class Solution {
 2     int [] parent;
 3     int [] size;
 4     
 5     public boolean validTree(int n, int[][] edges) {
 6         if(n < 0 || edges == null || edges.length != n-1){
 7             return false;
 8         }
 9         parent = new int[n];
10         size = new int[n];
11         for(int i = 0; i<n ;i++){
12             parent[i] = i;
13             size[i] = 1;
14         }
15         
16         for(int [] edge : edges){
17             if(!find(edge[0], edge[1])){
18                 union(edge[0], edge[1]);
19             }else{
20                 return false;
21             }
22         }
23         return true;
24     }
25     
26     private boolean find(int i, int j){
27         return root(i) == root(j);
28     }
29     private int root(int i){
30         while(i != parent[i]){
31             parent[i] = parent[parent[i]];
32             i = parent[i];
33         }
34         return i;
35     }
36     private void union(int p, int q){
37         int i = root(p);
38         int j = root(q);
39         if(size[i] < size[j]){
40             parent[i] = j;
41             size[j] += size[i];
42         }else{
43             parent[j] = i;
44             size[i] += size[j];
45         }
46     }
47 }

 

LeetCode Graph Valid Tree

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/5237914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!