Skip to content

Commit 6bdb021

Browse files
committed
[LeetCode Sync] Runtime - 43 ms (88.18%), Memory - 34.3 MB (29.62%)
1 parent 01fae43 commit 6bdb021

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>
2+
3+
<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [100,4,200,1,3,2]
10+
<strong>Output:</strong> 4
11+
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
18+
<strong>Output:</strong> 9
19+
</pre>
20+
21+
<p><strong class="example">Example 3:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> nums = [1,0,1,2]
25+
<strong>Output:</strong> 3
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
33+
<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
34+
</ul>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def longestConsecutive(self, nums: List[int]) -> int:
3+
hash_table = set(nums)
4+
result = 0
5+
6+
for num in hash_table:
7+
if num - 1 not in hash_table:
8+
val = num + 1
9+
while val in hash_table:
10+
val += 1
11+
result = max(result, val - num)
12+
13+
return result

0 commit comments

Comments
 (0)