Skip to content

Commit 26e9a1f

Browse files
committed
O(nlogn) time and O(1) space using sorting.
1 parent 4a75f4b commit 26e9a1f

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+
"""
2+
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
3+
4+
Your algorithm should run in O(n) complexity.
5+
6+
Example:
7+
8+
Input: [100, 4, 200, 1, 3, 2]
9+
Output: 4
10+
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
11+
"""
12+
class Solution:
13+
def longestConsecutive(self, nums: List[int]) -> int:
14+
if not nums:
15+
return 0
16+
result,count = 1,1
17+
nums.sort()
18+
for i in range(len(nums)-1):
19+
if nums[i+1] == nums[i] + 1:
20+
count += 1
21+
result = max(count,result)
22+
elif nums[i+1] == nums[i]:
23+
continue
24+
else:
25+
count = 1
26+
return result

0 commit comments

Comments
 (0)