128. Longest Consecutive Sequence
MediumLeetCodeGiven 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.
Example 1
Input: nums =
[100,4,200,1,3,2]Output:4Explanation: The longest consecutive elements sequence is[1, 2, 3, 4]. Therefore its length is4.
Example 2
Input: nums =
[0,3,7,2,5,8,4,6,0,1]Output:9
Example 3
Input: nums =
[1,0,1,2]Output:3
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
How to solve the problem
- Sorting
python
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums:
return 0
nums = sorted(set(nums))
current_len = 1
max_len = 1
for i in range(1, len(nums)):
if nums[i] == nums[i-1] + 1:
current_len += 1
max_len = max(current_len, max_len)
else:
current_len = 1
return max_len- Hashing
python
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = set(nums)
length = 0
max_length = 0
for num in nums:
if num - 1 not in nums:
length = 1
while num + length in nums:
length += 1
max_length = max(length, max_length)
return max_lengthComplexity
- Sorting: Time complexity: O(n log n), Space complexity: O(1)
- Hashing: Time complexity: O(n), Space complexity: O(n)
- Each element is visited at most twice (once in the outer loop, once in the inner while loop)
Comments
No comments yet. Be the first to comment!