LeetCode系列128—最长连续序列

题意

给定一个未排序的整数数组 nums,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

题解

方法一:哈希表

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> num_set;
        for(int num : nums)
            num_set.insert(num);
        int longestStreak = 0;
        for(int num : num_set){
            if(!num_set.count(num-1)){
                int currentNum = num;
                int currentStreak = 1;
                while(num_set.count(currentNum+1)){
                    currentNum++;
                    currentStreak++;
                }
                longestStreak = max(longestStreak, currentStreak);
            }
        }
        return longestStreak;
    }
};

方法二:并查集

class Solution {
private:
    unordered_map<int, int> parent, cnt;
public:

    int find(int num) {
        return num == parent[num] ? num : find(parent[num]);
    }
    
    int merge(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return cnt[x];
        cnt[x] += cnt[y];
        parent[y] = x;
        return cnt[x];
    }

    int longestConsecutive(vector<int>& nums) {
        if (nums.empty()) return 0;
        int ans = 1;
        for (int i = 0; i < nums.size(); i++) {
            parent[nums[i]] = nums[i];
            cnt[nums[i]] = 1;
        }
        for (int i = 0; i < nums.size(); i++) {
            if (cnt.count(nums[i] + 1)) {
                ans = max(ans, merge(nums[i], nums[i]+1));
            }
        }
        return ans;
    }
};

参考

最长连续序列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值