Longest Consecutive Sequence

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

找最长连续子序列

这种题目,我一看到,就往dp想,但是,dp果断构造不出O(n)的动态转移方程。。。所以。。不会做。。。。。

用排序是n*log n的。。。不给力。。

看到“待字闺中”正好发布了一个这个题目的思路。。。。好吧。。。我还是太年轻了,还是已经忘记了。。。典型的并查集

用一个map来维护数字和其对应的index

一个father数组和一个count数组,用count更多的是为了平衡,防止union set退化

每次新来一个数x,判断是否已经在map中,如果在则跳过,如果不在,将其加入到并查集中,father是自己

然后union(x,x+1),接着union(x,x-1)  

union的过程就是找到x和y分别各自的索引,然后找出该索引的father,然后更新father和count信息。

最后,遍历count数组,选出值最大的即可

class Solution {
public:
    vector<int> father;
    vector<int> count;
    map<int,int> index;
    int getIndex(int n){
        map<int,int>::iterator it = index.find(n);
        if(it==index.end())
            return -1;
        return it->second;
    }
    int getFather(int x){
        if(x==father[x])
            return x;
        return getFather(father[x]);
    }
    void uni(int x,int y){
        int xi = getIndex(x);
        int yi = getIndex(y);
        if(xi==-1 || yi==-1)
            return;
        int fx = getFather(xi);
        int fy = getFather(yi);
            
        if(count[fx]>count[fy]){
            father[fy] = fx;
            count[fx] = count[fx]+count[fy];
        }else{
            father[fx] = fy;
            count[fy] +=count[fx];
        }
    }
    int longestConsecutive(vector<int> &num) {
        for(int i=0;i<num.size();i++){
            if(getIndex(num[i])!=-1)
                continue;
            father.push_back(father.size());
            count.push_back(1);
            index.insert(pair<int,int>(num[i],father.size()-1));
            uni(num[i],num[i]+1);
            uni(num[i],num[i]-1);
        }
        int ma = 0;
        for(int i=0;i<count.size();i++)
            if(count[i]>ma)
                ma=count[i];
        return ma;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值