684 Redundant Connection

1. Question

n this problem, a tree is an undirected graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array ofedges. Each element ofedgesis a pair[u, v]withu < v, that represents an undirected edge connecting nodesuandv.
Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge[u, v]should be in the same format, withu < v.
Example 1:
1
Input: [[1,2], [1,3], [2,3]]
2
3
Output: [2,3]
4
5
Explanation:
6
The given undirected graph will be like this:
7
1
8
/ \
9
2 - 3
Copied!
Example 2:
1
Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
2
3
Output: [1,4]
4
5
Explanation:
6
The given undirected graph will be like this:
7
8
5 - 1 - 2
9
| |
10
4 - 3
Copied!
Note:
The size of the input 2D-array will be between 3 and 1000.
Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.

2. Implementation

(1) Union Find
1
class Solution {
2
public int[] findRedundantConnection(int[][] edges) {
3
int n = edges.length;
4
UnionFind uf = new UnionFind(n);
5
6
for (int[] edge : edges) {
7
if (!uf.union(edge[0], edge[1])) {
8
return new int[] {edge[0], edge[1]};
9
}
10
}
11
return new int[0];
12
}
13
14
class UnionFind {
15
int[] sets;
16
int[] size;
17
int count;
18
19
public UnionFind(int n) {
20
sets = new int[n + 1];
21
size = new int[n + 1];
22
count = n;
23
24
for (int i = 0; i <= n; i++) {
25
sets[i] = i;
26
size[i] = 1;
27
}
28
}
29
30
public int find(int node) {
31
while (node != sets[node]) {
32
node = sets[node];
33
}
34
return node;
35
}
36
37
public boolean union(int i, int j) {
38
int node1 = find(i);
39
int node2 = find(j);
40
41
if (node1 == node2) {
42
return false;
43
}
44
45
if (size[node1] < size[node2]) {
46
sets[node1] = node2;
47
size[node2] += size[node1];
48
}
49
else {
50
sets[node2] = node1;
51
size[node1] += size[node2];
52
}
53
54
--count;
55
return true;
56
}
57
}
58
}
Copied!

3. Time & Space Complexity

Union Find: 时间复杂度O(n), 空间复杂度O(n)