Longest Consecutive Sequence

本文介绍了一种寻找整数数组中最长连续序列的高效算法。利用HashSet实现O(n)的时间复杂度,通过查找并删除元素来确定连续序列的长度。
1.题目

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

给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4

2.算法

由于这道题需要算法复杂度为O(n),而很多排序算法复杂度为nlog(n),所以不适合用排序算法,而用hash来解决的方案,add, remove, contains 等方法的复杂度都是 O(1),所以可以用hashset来解决,这道题分两步解

1.把数组中的数放到hashset中,便于查找,

2,找到最大连续整数,我们可以任意选一个数,向两边找,找到就把他从表中删去

    public int longestConsecutive(int[] num) 
    {
        // write you code here
    	if (num == null || num.length == 0)
    	{
    		return 0;
    	}
    	HashSet<Integer> set = new HashSet<Integer>();
    	int res = 1;
    	for (int i = 0; i < num.length; i++)
    	{
    		set.add(num[i]);
    	}
    	while (!set.isEmpty())
    	{
    		Iterator<Integer> it = set.iterator();
    		int item = (int)it.next();
    		set.remove(item);
    		int len = 1;
    		int i = item - 1;
    		while (set.contains(i))
    		{
    			set.remove(i--);
    			len++;
    		}
    		i = item + 1;
    		while (set.contains(i))
    		{
    			set.remove(i++);
    			len++;
    		}
    		if (len > res)
    		{
    			res = len;
    		}
    	}
    	return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值