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;
}