|
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 | + */ |
10 | 8 |
|
11 | 9 | class Solution {
|
| 10 | + private Set<Integer> set; |
| 11 | + |
12 | 12 | 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()); |
17 | 16 |
|
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 | + } |
29 | 23 |
|
30 |
| - return answer; |
| 24 | + public int calculateLength(int num) { |
| 25 | + return (int) IntStream.iterate(num, n->n+1) |
| 26 | + .takeWhile(set::contains) |
| 27 | + .count(); |
31 | 28 | }
|
32 | 29 | }
|
0 commit comments