Skip to content

Commit 371bff6

Browse files
committed
✨ 128. Longest Consecutive Sequence
1 parent 7548c1d commit 371bff6

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
comments: true
3+
difficulty: mediuum
4+
# Follow `Topics` tags
5+
tags:
6+
- Array
7+
- Hash Table
8+
- Union Find
9+
---
10+
11+
# [128. Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/description/)
12+
13+
## Description
14+
Input is unsorted array integers, return the longest consecutive elements count.
15+
16+
**Example 1:**
17+
```
18+
Input: nums = [9,2,41,3,5,4]
19+
Output: 4
20+
```
21+
The longest consecutive elements is `[2, 3, 4, 5]`. Therefore its count is 4.
22+
23+
**Constraints:**
24+
25+
`0 <= nums.length <= 10^5`
26+
27+
`-10^9 <= nums[i] <= 10^9`
28+
29+
30+
## Solution
31+
For efficiency check num exist, conver nums to set.
32+
33+
Then loop and check the consecutive count.
34+
35+
Avoid duplicate checking num which in the middle of consecutive sqeuence, skip the check when `num - 1` exist.
36+
37+
```java
38+
class Solution {
39+
public int longestConsecutive(int[] nums) {
40+
Set<Integer> numSet = new HashSet<>();
41+
for (int num : nums) {
42+
numSet.add(num);
43+
}
44+
int longest = 0;
45+
for (int num : nums) {
46+
if (!numSet.contains(num - 1)) {
47+
int length = 1;
48+
while (numSet.contains(num + length)) {
49+
length++;
50+
}
51+
longest = Math.max(longest, length);
52+
}
53+
}
54+
return longest;
55+
}
56+
}
57+
```
58+
59+
## Complexity
60+
61+
- Time complexity: $O(n)$
62+
<!-- Add time complexity here, e.g. $$O(n)$$ -->
63+
64+
- Space complexity: $O(n)$
65+
<!-- Add space complexity here, e.g. $$O(n)$$ -->
66+
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int longestConsecutive(int[] nums) {
3+
Set<Integer> numSet = new HashSet<>();
4+
for (int num : nums) {
5+
numSet.add(num);
6+
}
7+
int longest = 0;
8+
for (int num : nums) {
9+
if (!numSet.contains(num - 1)) {
10+
int length = 1;
11+
while (numSet.contains(num + length)) {
12+
length++;
13+
}
14+
longest = Math.max(longest, length);
15+
}
16+
}
17+
return longest;
18+
}
19+
}

0 commit comments

Comments
 (0)