-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0128-longest-consecutive-sequence.kt
75 lines (63 loc) · 1.91 KB
/
0128-longest-consecutive-sequence.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import kotlin.math.max
class Solution {
fun longestConsecutive(nums: IntArray): Int {
if (nums.isEmpty()) return 0
if (nums.size == 1) return 1
val hashSet = HashSet<Int>()
nums.forEach { hashSet.add(it) }
var longestSize = 0
var isNumberStartOfSequence: Boolean
for (num in nums) {
isNumberStartOfSequence = !hashSet.contains(num - 1)
if (isNumberStartOfSequence) {
var nextConsecutiveNumber = num + 1
var currentSize = 1
while (hashSet.contains(nextConsecutiveNumber)) {
nextConsecutiveNumber++
currentSize++
}
longestSize = max(longestSize, currentSize)
}
}
return longestSize
}
}
// Alternative solution using Union Find
class Solution {
class DSU(val n: Int) {
val parent = IntArray(n) { it }
val size = IntArray(n) { 1 }
fun find(x: Int): Int {
if (parent[x] != x)
parent[x] = find(parent[x])
return parent[x]
}
fun union(x: Int, y: Int) {
val px = find(x)
val py = find(y)
if (px != py) {
parent[py] = px
size[px] += size[py]
}
}
fun getLongest(): Int {
var res = 0
for (i in parent.indices) {
if (parent[i] == i)
res = maxOf(res, size[i])
}
return res
}
}
fun longestConsecutive(nums: IntArray): Int {
val hm = HashMap<Int, Int>()
val dsu = DSU(nums.size)
for ((i,n) in nums.withIndex()) {
if (n in hm) continue
hm[n - 1]?.let { dsu.union(i, it) }
hm[n + 1]?.let { dsu.union(i, it) }
hm[n] = i
}
return dsu.getLongest()
}
}