Leetcode 128. Longest Consecutive Sequence 最长连续子序列 DFS,并查集

这篇博客介绍了如何利用深度优先搜索(DFS)和并查集(Disjoint Set)两种数据结构来解决寻找给定整数数组中最长连续子集的问题。在DFS实现中,通过记忆化搜索优化了搜索效率,而在并查集中,通过查找和合并操作高效地确定了最长连续序列。两种方法都以O(n)的时间复杂度完成任务。
摘要由CSDN通过智能技术生成

DFS

  • 每访问一个元素i,都直接去看i +1, i + 2… i + n直到这些元素不存在,通过记忆化搜索的方式,保证只会搜n次
class Solution {
public:
    unordered_map<int, int> dic;
    int dfs(int x){
        if(!dic.count(x)) return 0;
        if(dic[x] != 0) return dic[x];
        return dic[x] = dfs(x + 1) + 1;
    }
    int longestConsecutive(vector<int>& nums) {
        if(nums.size() == 0 ) return 0;
        int res = 1;
        for(auto e: nums){
            dic[e] = 0;
        }
        for(auto e: nums){
            res = max(res, dfs(e));
        }
        return res;
    }
};

并查集

class Solution {
public:
    unordered_map<int, int> par, count;
    int find(int v){
        return par[v] == v?v:par[v] = find(par[v]);
    }
    int merge(int u, int v){
        u = find(u);
        v = find(v);
        if(u != v){
            par[v] = par[u];
            count[u] += count[v];
        }
        return count[u];
    }
    int longestConsecutive(vector<int>& nums) {
        if(nums.size() == 0 ) return 0;
        int res = 1;
        for(auto e: nums){
            par[e] = e;
            count[e] = 1;
        }
        for(auto e: nums){
            if (count.count(e + 1) ) 
                res = max(res, merge(e + 1, e));
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值