如果不懂并查集概念的可以查看之前写过的并查集零基础介绍
思路
判断两个节点时候是连通的,如果连通则将它们合并到一个集合(树)中。 如果在判断过程中,发现在并查集中这两个节点已经是连通的了,说明此时这个连通条件是冗余的,即可以被删除的边,将这个集合返回即可
for ( int i = 0 ; i < edges. length; i++ ) {
if ( uf. isConnected ( edges[ i] [ 0 ] , edges[ i] [ 1 ] ) ) {
return edges[ i] ;
} else {
uf. meger ( edges[ i] [ 0 ] , edges[ i] [ 1 ] ) ;
}
}
代码实现(java)
class Solution {
class UnionFind {
private Map < Integer , Integer > father;
private int numOfSets = 0 ;
public UnionFind ( ) {
father = new HashMap < > ( ) ;
numOfSets = 0 ;
}
public void add ( int x) {
if ( ! father. containsKey ( x) ) {
father. put ( x, null ) ;
numOfSets++ ;
}
}
public int find ( int x) {
int root = x;
while ( father. get ( root) != null ) {
root = father. get ( root) ;
}
return root;
}
public void meger ( int x, int y) {
int rootX = find ( x) ;
int rootY = find ( y) ;
if ( rootX != rootY) {
father. put ( rootX, rootY) ;
numOfSets-- ;
}
}
public boolean isConnected ( int x, int y) {
return find ( x) == find ( y) ;
}
public int getNumOfSets ( ) {
return numOfSets;
}
}
public int [ ] findRedundantConnection ( int [ ] [ ] edges) {
UnionFind uf = new UnionFind ( ) ;
for ( int i = 0 ; i < edges. length; i++ ) {
if ( uf. isConnected ( edges[ i] [ 0 ] , edges[ i] [ 1 ] ) ) {
return edges[ i] ;
} else {
uf. meger ( edges[ i] [ 0 ] , edges[ i] [ 1 ] ) ;
}
}
return null ;
}
}