Longest Consecutive Sequence

Longest Consecutive Sequence

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.

 

解题思路:

题目大意:求最长连续子串。正常思路,排序数组,动态规划求解sorted数组的最长连续子串。按照这个思路思考下来。在内部排序算法中最快的算法时间复杂度为nlog(n),不符合题目的O(n)的要求。所以只能往基数排序,以及桶排序和hash这方面来考虑。

对于这道题,可以用hash实现,为了引人hash的功能,算法中借用了STL的map容器。

 

Code:

int longestConsecutive(vector<int> &num)
{
	map<int,bool> vmap;

	for(int i=0;i<num.size();i++)
		vmap[num[i]]=true;

	int ant=0;
	for(int i=0;i<num.size();i++)
	{
		if(vmap[num[i]]==true)
		{
			vmap[num[i]]=false;
			int count=1;
			int left=num[i]-1;
			while(vmap[left]==true)
			{
				vmap[left--]=false;
				count++;
			}
			int right=num[i]+1;
			while(vmap[right]==true)
			{
				vmap[right++]=false;
				count++;
			}
			ant=max(ant,count);
		}
	}
	return ant;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值