[NeetCode 150] Longest Consecutive Sequence

Longest Consecutive Sequence

Given an array of integers nums, return the length of the longest consecutive sequence of elements.

A consecutive sequence is a sequence of elements in which each element is exactly 1 greater than the previous element.

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [2,20,4,10,3,4,5]

Output: 4

Explanation: The longest consecutive sequence is [2, 3, 4, 5].

Example 2:

Input: nums = [0,3,2,5,4,6,1,1]

Output: 7

Constraints:

0 <= nums.length <= 1000
-10^9 <= nums[i] <= 10^9

Solution

According to example 2, we can know that “sequence” here can shuffle the original order in the input array. Therefore, the order and number of the numbers in input array is not important, and we can just store them in a set() for easy searching.

After that, we can do a Memorized Search, record the longest sequence length of each number when the number is as the start number of the sequence. We can store this in a dictionary, where the key is the number and the value is the longest sequence length. Therefore, we can directly get the length of next consecutive number if the next number has already been searched. This will reduce the time complexity of search from O ( n 2 ) O(n^2) O(n2) to O ( n ) O(n) O(n)

Code

To write the process elegantly, I realize it by DFS.

If the number has been searched, then its longest sequence value will appear in the dictionary, just return it;
If the number has not been searched, check if the next consecutive number exists.
If the next number exists, go to the next one and return 1+returned value, or just return 1.

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        num_set = set(nums)
        length_dict = {}
        def dfs(number: int) -> int:
            if number in length_dict:
                return length_dict[number]
            if number+1 not in num_set:
                length_dict[number] = 1
                return length_dict[number]
            length_dict[number] = dfs(number+1) + 1
            return length_dict[number]
        answer = 0
        for num in num_set:
            if num not in length_dict:
                answer = max(answer, dfs(num))
        return answer
        
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值