Skip to content

Commit 866136b

Browse files
committed
longest consecutive sequence
1 parent 03ee829 commit 866136b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public int longestConsecutive(int[] nums) {
3+
Set<Integer> set = Arrays.stream(nums)
4+
.boxed()
5+
.collect(Collectors.toSet());
6+
7+
return set.stream()
8+
.map(num -> {
9+
if (set.contains(num - 1)) {
10+
return 0;
11+
}
12+
13+
int consecutiveLength = 1;
14+
15+
while (set.contains(num + 1)) {
16+
consecutiveLength += 1;
17+
num += 1;
18+
}
19+
20+
return consecutiveLength;
21+
})
22+
.mapToInt(num -> num)
23+
.max()
24+
.orElse(0);
25+
}
26+
}

0 commit comments

Comments
 (0)