leetcode每日一题 128.最长连续序列(并查集)

本文深入探讨了两种求解最长连续整数序列的算法:并查集和哈希表。并查集方法通过遍历数组并合并连续元素,而哈希表方法利用集合特性快速查找连续元素。文章提供了详细的代码实现,帮助读者理解算法原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

并查集

思路

并查集,遍历数组,如果该数字+1在数组中则将它们合并。

代码

class Solution {
    unordered_map<int,int> father,cnt;
    int Find(int x)
    {
        int r = x;
        while(r!=father[r])
        {
            r = father[r];
        }
        int i = x;
        int j;
        while(father[i]!=i)
        {
            j = father[i];
            father[i] = r;
            i = j;
        }
        return r;
    }
    int Union(int x, int y)
    {
        int fx = Find(x);
        int fy = Find(y);
        if(fx==fy)
            return cnt[fx];
        if(fx<fy)
        {
            father[fy] = fx;
            cnt[fx] += cnt[fy];
            return cnt[fx];
        }
        else {
            father[fx] = fy;
            cnt[fy] += cnt[fx];
            return cnt[fy];
        }
    }
public:
    int longestConsecutive(vector<int>& nums) {
        int N = nums.size();
        if(N<1)
            return 0;
        for(auto x:nums)
        {
            father[x] = x;
            cnt[x] = 1;
        }
        int ans = 1;
        for(auto x : nums)
        {
            if(father.find(x+1)!=father.end())
            {
                ans = max(ans,Union(x,x+1));
            }
        }
        return ans;
    }
};

哈希表

思路

使用集合。

代码

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if(nums.size()==0)
            return 0;
        unordered_set<int> st;
        for(int x:nums)
        {
            st.insert(x);
        }
        int ans = 1;
        for(int x:nums)
        {
            if(st.count(x-1))
                continue;
            int cnt = 1;
            int t = x;
            while(st.count(t+1))
            {
                cnt++;
                t++;
            }
            ans = max(ans,cnt);
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值