Simple O(n) solution using unordered set


#1

int Solution::longestConsecutive(const vector &A) {
unordered_set mset;
for(int i=0; i<A.size();i++){
mset.insert(A[i]);
}
int best=0;
for(int i=0; i<A.size();i++){
if(mset.find(A[i]-1)==mset.end()){
int currlength=1;
int j=1;
while(1){
if( mset.find(A[i]+j) != mset.end() )
currlength++;
else break;
j++;
}
best = best<currlength ? currlength:best;
}
}
return best;
}