Problem
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Constraints:
- 0 <= nums.length <= 105
- -109 <= nums[i] <= 109
Algorithm
This is not the O(n) solution. First sort the data and find the longest consecutive sequence。
Code
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums:
return 0
Lnums = len(nums)
nums.sort()
new_nums = [nums[0]]
sLen = 1
for i in range(1, Lnums):
if nums[i] != new_nums[sLen-1]:
sLen += 1
new_nums.append(nums[i])
ans = 1
cnt = 1
for i in range(1, sLen):
if new_nums[i] == new_nums[i-1] + 1:
cnt += 1
else:
cnt = 1
if ans < cnt:
ans = cnt
return ans