Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
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.
#define tr(c,it) for(decltype((c).begin()) (it) = (c).begin(); (it) != (c).end(); (it)++)
int longestConsecutive(vector<int> &num) {
int res = 1,local = 1;
int n = num.size();
if(n==0)return 0;
sort(num.begin(),num.end());
set<int> s;
tr(num, it)
{
s.insert(*it);
}
num.clear();
n = 0;
tr(s, it)
{
num.push_back(*it);
n++;
}
for (int i = 1; i < n; i++)
{
if(num[i] == num[i-1]+1)
{
local++;
if(local > res)res = local;
}
else
local = 1;
}
return res;
}
No comments:
Post a Comment