leetcode:数组之Longest Consecutive Sequence,
给定一个乱序的数组,输出数组中连续的序列长度,例如,输入a=[100,4,200,1,3,2],输出最大连续序列长度length=4;
分析:由于数组为无序数组,则首先想到哈希表,即利用一个哈希表unordered_map<int,bool> used 记录每个元素是否使用,对每个元素,以该元素为中心,向左右扩张,直到不连续为止,记录最长的长度。
实现:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int longestConsecutive(vector<int> num)
{
unordered_map<int,bool> used;
for(auto i:num) used[i]=false;
int longest=0;
for(auto i:num)
{
if(used[i]) continue;
int length=1;
used[i]=true;
for(int j=i+1;used.find(j)!=used.end();++j)
{
used[j]=true;
++length;
}
for(int j=i-1;used.find(j)!=used.end();--j)
{
used[j]=true;
++length;
}
longest =max (longest,length);
}
return longest;
}
int main()
{
int a[6]={100,4,200,1,3,2};
vector<int> arr(a,a+6);
int length=0;
length=longestConsecutive(arr);
cout<<"最长有序序列的长度为:"<<length<<endl;
return 0;
}
测试结果: