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