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.
Algorithm:
1. unordered_set is needed to be the hashtable.
2. for each one check the whole consecutive sequence containing it. and on each check delete the checked ones.
My Code:
int longestConsecutive(vector<int> num) {
// use unordered_set to insert and find for constant.
unordered_set<int> numset;
for(int i = 0; i < num.size(); ++i)
numset.insert(num[i]);
int len = 1;
for(int i = 0; i < num.size(); ++i){
int u = num[i];
int v = u;
int count = 1;
if(numset.find(v)!=numset.end()){
numset.erase(v);
while(numset.find(--v)!=numset.end()){
numset.erase(v);
++count;
}
v = u;
while(numset.find(++v)!=numset.end()){
numset.erase(v);
++count;
}
if(count < len){
len = count;
}
}
}
return len;
}
No comments:
Post a Comment