Skip to content

Commit 8f6b16b

Browse files
longest consecutive sequence using union find
1 parent 057ee23 commit 8f6b16b

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package hard;
2+
3+
import java.util.*;
4+
/**
5+
* Created by fishercoder1534 on 9/30/16.
6+
*/
7+
public class LongestConsecutiveSequence {
8+
//inspired by this solution: https://discuss.leetcode.com/topic/29286/my-java-solution-using-unionfound
9+
public int longestConsecutive(int[] nums) {
10+
Map<Integer, Integer> map = new HashMap();//<value, index>
11+
UnionFind uf = new UnionFind(nums);
12+
for(int i = 0; i < nums.length; i++){
13+
if(map.containsKey(nums[i])) continue;
14+
map.put(nums[i], i);
15+
if(map.containsKey(nums[i]-1)){
16+
uf.union(i, map.get(nums[i]-1));//note: we want to union this index and nums[i]-1's root index which we can get from the map
17+
}
18+
if(map.containsKey(nums[i]+1)){
19+
uf.union(i, map.get(nums[i]+1));
20+
}
21+
}
22+
return uf.maxUnion();
23+
}
24+
25+
class UnionFind{
26+
int[] ids;
27+
28+
public UnionFind(int[] nums){
29+
ids = new int[nums.length];
30+
for(int i = 0; i < nums.length; i++) ids[i] = i;
31+
}
32+
33+
public void union(int i, int j){
34+
int x = find(ids, i);
35+
int y = find(ids, j);
36+
ids[x] = y;
37+
}
38+
39+
public int find(int[] ids, int i){
40+
while(i != ids[i]){
41+
ids[i] = ids[ids[i]];
42+
i = ids[i];
43+
}
44+
return i;
45+
}
46+
47+
public boolean connected(int i, int j){
48+
return find(ids, i) == find(ids, j);
49+
}
50+
51+
public int maxUnion(){//this is O(n)
52+
int max = 0;
53+
int[] count = new int[ids.length];
54+
for(int i = 0; i < ids.length; i++){
55+
count[find(ids, i)]++;
56+
max = max < count[find(ids, i)] ? count[find(ids, i)] : max;
57+
}
58+
return max;
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)