feat(0128_longest-consecutive-sequence): add py3 solution
This commit is contained in:
24
0128_longest-consecutive-sequence/python3/nlogn.py
Normal file
24
0128_longest-consecutive-sequence/python3/nlogn.py
Normal file
@@ -0,0 +1,24 @@
|
||||
# Time: O(NlogN)
|
||||
# Space: O(1)
|
||||
class Solution:
|
||||
def longestConsecutive(self, nums: List[int]) -> int:
|
||||
nums.sort()
|
||||
|
||||
max_length = 1
|
||||
l = 1
|
||||
|
||||
# We don't want to go OOB
|
||||
for i in range(0, len(nums) - 1):
|
||||
diff = nums[i + 1] - nums[i]
|
||||
|
||||
# All good, still consecutive.
|
||||
if diff == 1:
|
||||
l += 1
|
||||
max_length = max(max_length, l)
|
||||
# We skip to next iteration of loop if
|
||||
# item repeats. Otherwise, we reset
|
||||
# running length variable to 1
|
||||
elif diff != 0:
|
||||
l = 1
|
||||
|
||||
return max_length if len(nums) > 0 else 0
|
||||
Reference in New Issue
Block a user