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.


看到这个问题肯定会想到先把数组进行排序,但是排序算法的时间复杂度至少是NLog(N),因此不可能进行排序。当时真是一头雾水,觉得没有办法把时间复杂度控制在O(N),后来实在想不通就上网找了些资料,发现可以通过散列表来做。散列表的定义为Hash table,也叫哈希表),是根据关键字(Key value)而直接访问在内存存储位置的数据结构。也就是说,它通过把键值通过一个函数的计算,映射到表中一个位置来访问记录,这加快了查找速度。这个映射函数称做散列函数,存放记录的数组称做散列表。后来又看到这篇博客从头到尾彻底解析Hash 表算法),于是又更加深刻的理解了哈希表算法。采用STL里面的unordered_map成功解决了这个问题。

其中还涉及到auto这个关键字,以前没用过。由于新的C++标准,auto关键字有了一些新的含义。

基于以下两个原因,尽可能使用auto:首先,使用auto会避免重复声明编译器已经知道的类型。其次,当使用未知类型或者类型名称不易理解时使用auto会更加便利。

// C++98 
binder2nd< greater<int> > x = bind2nd( greater<int>(), 42 ); 
  
// C++11 
auto x = [](int i) { return i > 42; };

// C++98 
map<int,string>::iterator i = m.begin(); 
  
// C++11 
auto i = begin(m);

// C++98 
for( vector<double>::iterator i = v.begin(); i != v.end(); ++i ) { 
total += *i; 
} 
  
// C++11 
for( auto d : v ) { 
total += d; 
}


class Solution {
public:
	int longestConsecutive(const vector<int> &num) {
		unordered_map<int, bool>visited;
		int length = 0;
		int finalLength = 0;
		for (auto i:num)
			visited[i] = false;
		for (auto i : num)
		{
			if (visited[i])
				continue;
			length = 1;
			for (int j = i + 1; visited.find(j) != visited.end(); ++j)
			{
				++length;
				visited[j]=true;
			}
			for (int m = i - 1; visited.find(m) != visited.end(); --m)
			{
				++length;
				visited[m] = true;
			}
			finalLength = max(finalLength,length);
		}
		return finalLength;
	}
};


auto关键字介绍参考:http://www.cnblogs.com/hmxp8/archive/2011/11/15/2249309.html




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值