26、最长连续序列
题目:给定一个任意整数序列,返回序列中最长连续序列的长度。如[100, 4, 200, 1, 3, 2],最长连续序列为[1,2,3,4],返回长度4。要求时间复杂度为O(n)
分析:如果允许O(n log n) 的复杂度,那么可以先排序,可是本题要求O(n)。由于序列里的元素是无序的,又要求O(n),首先要想到用哈希表。用一个哈希表hash_map<int, bool> used 记录每个元素是否使用,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。
#include<iostream>
#include <hash_map>
#include <vector>
using namespace std;
using stdext::hash_map;
int longestConsecutive(const vector<int> &num)
{
hash_map<int, bool> used;
for (int i=0;i<num.size();i++)
used[num[i]] = false;
int longest = 0;
for (int i=0;i<num.size();i++)
{
if (used[num[i]]) continue;
int length = 1;
used[num[i]] = true;
for (int j = num[i] + 1; used.find(j) != used.end(); ++j)
{
used[j] = true;
++length;
}
for (int j = num[i] - 1; used.find(j) != used.end(); --j)
{
used[j] = true;
++length;
}
longest = max(longest, length);
}
return longest;
}
注:在vs2008中使用hashmap时,出现错误:
error C2065: “hash_map”: 未声明的标识符。
这是因为hash_map目前是vs2008的一个扩展,并没有在标准的c++中。要想使用hash_map,需要using namespace stdext;但是,这很可能产生命名空间冲突,可以加上:using stdext::hash_map.