Longest Consecutive Sequence(最长连续序列)

本文介绍了一种寻找数组中最长连续整数序列的算法,并提供了一个具体实现案例。该算法使用哈希集合存储数组元素,通过左右扫描的方式找到最长连续序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目原型:

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.

基本思路:

题目的意思就是给你一个数组,让你找出数组中的最长连续序列,顺序可变。这个题可以采取利用空间换取时间的算法,先将这个数组的值放入hashset中,然后遍历数组,当取得数组中的一个值时,分别从左边和右边算出他的连续值,最后查询这个连续词是否在hashset中,在的话就将length+1,否则更新最大的length。如,对于数组中的第二个数4,向左边查找3,2,1、、、、是否在hashset中,然后查找5,6,7、、、是否在hashset中,直到找不到时更新最大的length值。

	public int longestConsecutive(int[] num) 
	{
		int max = 0;
		int sum = 0;
		if(num.length==0)
			return 0;
		Set<Integer> set = new HashSet<Integer>();
		int i = num.length-1;
		while(i>=0)
		{
			set.add(num[i]);
			i--;
		}
		for(i = 0;i<num.length;i++)
		{
			sum = 0;
			if(set.contains(num[i]))
			{
				sum++;
				set.remove(num[i]);
				int number = num[i];
				//查找左边
				while(true)
				{
					number--;
					if(set.contains(number))
					{
						set.remove(number);
						sum++;
					}
					else
						break;
				}
				number = num[i];
				//查找右边
				while(true)
				{
					number++;
					if(set.contains(number))
					{
						set.remove(number);
						sum++;
					}
					else
						break;
				}
				max = max>sum?max:sum;
			}
			
		}
		return max;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值