Skip to content

Commit 3efceae

Browse files
committed
feat: longest-consecutive-sequence
1 parent f3c3425 commit 3efceae

File tree

1 file changed

+22
-25
lines changed

1 file changed

+22
-25
lines changed
Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,29 @@
1-
/*
2-
Problem: https://leetcode.com/problems/longest-consecutive-sequence/
3-
Description: return the length of the longest consecutive elements sequence
4-
Concept: Array, Hash Table, Union Find
5-
Time Complexity: O(n), Runtime: 1141ms
6-
Space Complexity: O(n), Memory: 66.74MB
7-
*/
8-
import java.util.HashSet;
9-
import java.util.Set;
1+
/**
2+
* <a href="https://leetcode.com/problems/longest-consecutive-sequence/">week01-4.longest-consecutive-sequence</a>
3+
* <li> Description: return the length of the longest consecutive elements sequence </li>
4+
* <li> Concept: Array, Hash Table, Union Find </li>
5+
* <li> Time Complexity: O(n), Runtime: 60ms </li>
6+
* <li> Space Complexity: O(n), Memory: 55.7MB </li>
7+
*/
108

119
class Solution {
10+
private Set<Integer> set;
11+
1212
public int longestConsecutive(int[] nums) {
13-
Set<Integer> set = new HashSet<>();
14-
for(int num: nums) {
15-
set.add(num);
16-
}
13+
set = Arrays.stream(nums)
14+
.boxed()
15+
.collect(Collectors.toSet());
1716

18-
int answer = 0;
19-
for(int num: nums){
20-
if(set.contains(num-1)){ //contains(): O(1)
21-
continue;
22-
}
23-
int length = 1;
24-
while (set.contains(num+length)){
25-
length++;
26-
}
27-
answer = Math.max(answer, length);
28-
}
17+
return set.stream()
18+
.filter(num -> !set.contains(num-1))
19+
.map(this::calculateLength)
20+
.max(Integer::compareTo)
21+
.orElse(0);
22+
}
2923

30-
return answer;
24+
public int calculateLength(int num) {
25+
return (int) IntStream.iterate(num, n->n+1)
26+
.takeWhile(set::contains)
27+
.count();
3128
}
3229
}

0 commit comments

Comments
 (0)