Longest Consecutive Sequence

本文介绍了一种在O(n)复杂度下查找给定无序整数数组中最长连续序列的算法。通过利用哈希表以空间换取时间,实现快速查找连续元素并更新最长序列长度。

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

LeetCode Longest Consecutive Sequenc

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.


题目要求在O(n)中解决,因此普通的先排序再进行找的方法不行,因为最快的快排都要O(nlog(n))时间

因此肯定要使用其他的办法,要加强时间的缩减,因此可以利用哈希算法:以空间换取时间!


思路:由于需要查找最长连续的序列,因此可以考虑遍历数组,对于数组中的任意元素,查找它前面和后面的连续元素,每查找到就让计数器增一,最终记录最大的数目就是最长的序列。要注意的是每次查找的过程都可以删除找过的元素,因为最大长度始终记录在计数器中。


int longestConsecutive(vector<int> &num)
{
	int len = num.size();
	map<int, int> hashTable;
	for(int i=0; i<len; ++i)
	{
		hashTable.insert(pair<int, int>(num[i], i));
	}

	int res = 0, count = 0;
	//遍历数组中的每个元素,取出每个元素进行查找
	for(int i=0; i<len; i++)
	{
		//取出数组中第i个元素
		int number = num[i];
		map<int, int>::iterator it = hashTable.find(num[i]);
		count++;
		//如果在哈希表中找到num【i】,则找它前面和后面的元素,并统计总个数
		if(it!=hashTable.end())
		{
			while(true)
			{
				//找比num[i]大,并且连续的元素,++number,一个一个的向前找
				map<int, int>::iterator it_tmp = hashTable.find(++number);
				if(it_tmp==hashTable.end())
					break;
				count++;
				hashTable.erase(it_tmp);
			}

			number = num[i];
			while(true)
			{
				//找比num[i]小,并且连续的元素,--number,一个一个的向后找
				map<int, int>::iterator it_tmp = hashTable.find(--number);
				if(it_tmp == hashTable.end())
					break;
				count++;
				hashTable.erase(it_tmp);
			}

			if(res < count)
				res = count;			
		}
		count=0;
	}

	return res;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值