[leetcode] 128. Longest Consecutive Sequence

Description

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

分析

题目的意思是:给你一个数组,找求最长连续串的长度。

  • 首先建立一个hash表,然后初始化存储所有的数据元素。遍历数组,然后去找相关的hash表的值,如果找到了,就删除,并且重复遍历其相邻的hash表的值。就行了

C++

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> hashSet(nums.begin(),nums.end());
        int res=0;
        for(int val:nums){
            if(!hashSet.count(val)){
                continue;
            }
            hashSet.erase(val);
            int pre=val-1;
            int next=val+1;
            while(hashSet.count(pre)){
                hashSet.erase(pre);
                pre--;
            }
            while(hashSet.count(next)){
                hashSet.erase(next);
                next++;
            }
            res=max(res,next-pre-1);
        }
        return res;
    }
};

Python

通过hashset来判断数值是否连续,能够实现O(1)的时间复杂度,否则的话就要从头到尾的找,这样就是O(n)的复杂度了。另外为了减少重复的查找操作,我们从最小数开始,即在遍历的时候加了一个判断,参考代码。

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if len(nums)==0:
            return 0
        max_len = 1
        num_set = set(nums)
        for num in nums:
            if num -1 not in num_set:
                cur_num = num
                cur_count = 1
                while cur_num+1 in num_set:
                    cur_num+=1
                    cur_count+=1
                max_len = max(max_len, cur_count)
        return max_len

参考文献

[编程题]longest-consecutive-sequence

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值