最长连续序列

题目:给定一个未排序的整数数组,找出最长连续序列的长度。
例子:给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4。
挑战:要求你的算法复杂度为O(n)。

方法:。将序列中的所有数存到一个unordered_set中。对于序列里任意一个数A[i],我们可以通过set马上能知道A[i]+1和A[i]-1是否也在序列中。如果在,继续找A[i]+2和A[i]-2,以此类推,直到将整个连续序列找到。为了避免在扫描到A[i]-1时再次重复搜索该序列,在从每次搜索的同时将搜索到的数从set中删除。直到set中为空时,所有连续序列搜索结束。由于每个数字只被插入set一次,并删除一次,所以算法是O(n)的。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int, bool> hash;
        for (int i = 0; i < nums.size(); i++) {
            hash[nums[i]] = true;
        }

        int max = 0;
        for (int i = 0; i < nums.size(); i++) {
            int up = nums[i];
            while (hash.find(up) != hash.end()) {
                hash.erase(up);
                up++;
            }
            int down = nums[i] - 1;
            while (hash.find(down) != hash.end()) {
                hash.erase(down);
                down--;
            }
            if (up - down - 1 > max) {
                max = up - down - 1;
            }
        }
        return max;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值