Redundant Connection (684)
此题是明显的Union Find的问题。
和Mini Spining tree相似, 如果加入的新边使得原有的数据形成了环(就是union的结果是有相同的父亲)。说明这个边不应该加入
首先还是套路写一个Union Find的class
class UnionFind{ Map<Integer, Integer> father; public UnionFind(int n){ father = new HashMap<>(); for(int i = 1 ; i <= n ; ++i){ father.put(i,i); } } public void union(int a, int b){ int father_a = find(a) ; int father_b = find(b) ; if(father_a != father_b){ father.put(father_a, father_b); } } private int find(int a){ int father_a = father.get(a); if(father_a!= a){ father_a = find(father_a); } father.put(a, father_a); return father_a; } public boolean isValid(int a, int b){ return find(a) != find(b); } }
主函数调用
public int[] findRedundantConnection(int[][] edges) { if(edges.length == 0) return new int[0]; UnionFind uf = new UnionFind(edges.length); for(int i = 0 ; i < edges.length; ++i){ int a = edges[i][0]; int b = edges[i][1]; if(uf.isValid(a, b)){ uf.union(a,b); }else{ return edges[i]; } } return new int[0]; } }