最长连续序列

问题描述

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为  O(n)

示例:

[1, 2, 3, 4]。它的长度为 4。

代码实现

思路:用一个字典存储中间值遍历数组,对于数字I,找到的i-1和i + 1的对应的值值,如果不存在则记为0。然后把我的值值设为I-1,I + 1个的值值之和,并加1,相当于连接起来。同时置最左端和最右端的数的值值为我的值值(中间的数都已经出现过,不会再用到了)。然后更新一次最大值。

代码如下:

public class Solution {
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    public int longestConsecutive(int[] num) {
        // write you code here
        if(num.length <= 1)
            return num.length;
        Set<Integer> set = new HashSet<Integer>();
        for(int e:num)
            set.add(e);
        int max = 1;
        for(int e:num){
            int  count = 1;
            int left = e - 1;
            int right = e + 1;
            while(set.contains(left)){
                count++;
                set.remove(left);
                left--;
            }
            while(set.contains(right)){
                count++;
                set.remove(right);
                right++;
            }
            max = Math.max(max,count);
        }
        return max;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值