最长的连续序列的长度(Longest Consecutive Sequence)

Q: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.

A:使用Map来处理。对cluster来说,最重要的是上界,下界和长度。

对于a[i],只需要检查a[i]-1,a[i]+1

映射上界下界到区间长度。merge 相邻的cluster时,只需要更新上界和下界对应的区间长度。

//1. The key factors about a cluster is: lowest, highest, and length.
//2. Map lowest and highest to length. To merge two neighbor clusters, only need to update it's new lowest and highest, with new length.
//3. For every a[i], checking its neighbor a[i]-1 and a[i]+1 is enough. 
int merge(map<int, int>& hmap, int left, int right)
{
	int lower = left - hmap[left] + 1;//新区间的下届
	int upper = right + hmap[right] - 1; //新区间的上届

	int len = upper - lower + 1;
	hmap[lower] = len;
	hmap[upper] = len;
	return len;
}

int max(int i, int j)
{
	return i > j ? i : j;
}

int longestConsecutive(vector<int> &num) {
	// Start typing your C/C++ solution below
	// DO NOT write int main() function

	if (num.empty())
		return 0;

	int maxlen = 1;            //注意,初始化时1,而不是0

	map<int, int> hmap;

	for (int i = 0; i < num.size(); i++)
	{
		if (hmap.find(num[i]) != hmap.end())  //duplidate
			continue;
		hmap[num[i]] = 1;
		if (hmap.find(num[i] - 1) != hmap.end()) //在map容器中查找左边元素
		{
			maxlen = max(maxlen, merge(hmap, num[i] - 1, num[i]));
		}

		if (hmap.find(num[i] + 1) != hmap.end()) //在map容器中查找右边元素
		{
			maxlen = max(maxlen, merge(hmap, num[i], num[i] + 1));
		}
	}

	return maxlen;
}

参考:https://www.cnblogs.com/summer-zhou/archive/2013/09/17/3326652.html?from=singlemessage&isappinstalled=0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值