-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path128.py
More file actions
33 lines (23 loc) · 662 Bytes
/
Copy path128.py
File metadata and controls
33 lines (23 loc) · 662 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def longestConsecutive(nums: list[int]) -> int:
if not nums:
return 0
nums.sort()
previous = 0.5 # Set to 0.5 to ensure it doesn't coincide with any integer values in the array
longest = 1
current = 1
for num in nums:
if num == previous:
continue
if num == previous + 1:
current += 1
else:
current = 1
if current > longest:
longest = current
previous = num
return longest
print(longestConsecutive([100, 4, 200, 1, 3, 2]))
print(longestConsecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]))
# Complexity:
# Time: O(n log n)
# Space: O(n)