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.

首先最native的方法就是用一个数组记录数c是否出现,然后再从左到右遍历,看看连续最长的序列是多长。但这么做一个是空间复杂度太高,而且遇到负数不好处理。。

我们大可不必用这么大的数组来记录已经遍历的信息。
我们用一个lmap和一个rmap记录,map中的key是数组中的数,value是记录最长向右(左)能延伸的距离。

然后我们需要考虑下面几种情况。
比如已经遍历了 [ 1, 2,4,5 ,8,9,10]
1 ,数已经出现,比如下一个数字是2,则continue,跳过。
2 数c未出现,数c+1出现,数c-1没出现,比如下一个数字是7,因为7+1=8出现了,
那么需要执行两个操作:
(1)c可以向右扩展rmap[c+1]+1个长度
也就是把rmap[7]设为rmap[8]+1 ,
(2)c的最右边的数,可以向左扩展rmap[c+1]+1个长度
而把7向右走到头的最后一个数(也就是10)的lmap设为7的rmap的值。也就是执行lmap[10]= rmap[7]
3 数c未出现,数c-1出现,数c+1没出现 同上,就是变个方向
4 数c未出现,数c-1出现,数c+1出现,只需要把c-1向左走到头的数的rmap,和c+1向右走到头的数的lmap更新成。rmap[c+1]+lmap[c-1]+1
比如下一个数是3,就可以吧rmap[1]设为5,把lmap[5]设为5.
最后找lmap或rmap中最大的值即可。

    public int longestConsecutive(int[] nums) {
    HashMap<Integer,Integer> lmap = new HashMap<>();
    HashMap<Integer,Integer> rmap = new HashMap<>();
    for(int c :nums){
       if(lmap.containsKey(c)) {
         continue;
       }
        lmap.put(c, 1);
        rmap.put(c, 1);
        if(lmap.containsKey(c-1)&&rmap.containsKey(c+1)){
            int r = rmap.get(c+1);
            int l = lmap.get(c-1);
            lmap.put(c+r,l+r+1);
            rmap.put(c-l,l+r+1);
        }else {
            if (lmap.containsKey(c - 1)) {
                int l = lmap.get(c-1);
                lmap.put(c, l+1);
                rmap.put(c-l,l+1);
            }
            if (rmap.containsKey(c + 1)) {
                int r = rmap.get(c+1);
                rmap.put(c, r+1);
                lmap.put(c+r,r+1);
            }
        }
    }
    int max = 0;
    for (Map.Entry<Integer,Integer> entry:lmap.entrySet()){
        max = Math.max(max,entry.getValue());
    }
    return max;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值