C++ hashing with unordered map


#1

int Solution::longestConsecutive(const vector &A) {
if(A.empty()) return 0;
unordered_map<int,int> mp;
for(int i=0;i<A.size();i++){
mp[A[i]]=i;
}
vector tmp(A.size(),1);
for(int i=0;i<A.size();i++){
if(mp.find(A[i]-1)!=mp.end()) continue;
int j=i;
while(mp.find(A[j]+1)!=mp.end()){
int x=mp[A[j]+1];
tmp[x] = max(tmp[x],tmp[j]+1);
j = x;
}
}
return *max_element(tmp.begin(),tmp.end());
}