File tree Expand file tree Collapse file tree 1 file changed +51
-1
lines changed Expand file tree Collapse file tree 1 file changed +51
-1
lines changed Original file line number Diff line number Diff line change @@ -22,4 +22,54 @@ class Solution {
22
22
}
23
23
return longestSize
24
24
}
25
- }
25
+ }
26
+
27
+ // Alternative solution using Union Find
28
+ class Solution {
29
+
30
+ class DSU (val n : Int ) {
31
+ val parent = IntArray (n) { it }
32
+ val size = IntArray (n) { 1 }
33
+
34
+ fun find (x : Int ): Int {
35
+ if (parent[x] != x)
36
+ parent[x] = find(parent[x])
37
+ return parent[x]
38
+ }
39
+
40
+ fun union (x : Int , y : Int ) {
41
+ val px = find(x)
42
+ val py = find(y)
43
+ if (px != py) {
44
+ parent[py] = px
45
+ size[px] + = size[py]
46
+ }
47
+ }
48
+
49
+ fun getLongest (): Int {
50
+ var res = 0
51
+ for (i in parent.indices) {
52
+ if (parent[i] == i)
53
+ res = maxOf(res, size[i])
54
+ }
55
+ return res
56
+ }
57
+ }
58
+
59
+
60
+ fun longestConsecutive (nums : IntArray ): Int {
61
+ val hm = HashMap <Int , Int >()
62
+ val dsu = DSU (nums.size)
63
+
64
+ for ((i,n) in nums.withIndex()) {
65
+ if (n in hm) continue
66
+
67
+ hm[n - 1 ]?.let { dsu.union(i, it) }
68
+ hm[n + 1 ]?.let { dsu.union(i, it) }
69
+
70
+ hm[n] = i
71
+ }
72
+
73
+ return dsu.getLongest()
74
+ }
75
+ }
You can’t perform that action at this time.
0 commit comments