Skip to content

Commit 50a2ffb

Browse files
committed
Add longest consecutive sequence solution
1 parent d3a4c76 commit 50a2ffb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package leetcode_study
2+
3+
class Solution {
4+
fun longestConsecutive(nums: IntArray): Int {
5+
if (nums.isEmpty()) return 0
6+
7+
val sortedNums = nums.sorted()
8+
var maxLength = 1
9+
var currentLength = 1
10+
11+
for (i in 1 until sortedNums.size) {
12+
when {
13+
sortedNums[i] == sortedNums[i - 1] -> continue
14+
sortedNums[i] == sortedNums[i - 1] + 1 -> {
15+
currentLength++
16+
maxLength = maxOf(maxLength, currentLength)
17+
}
18+
else -> currentLength = 1
19+
}
20+
}
21+
22+
return maxLength
23+
}
24+
}

0 commit comments

Comments
 (0)