这道题非递归更直观,递归的写法纯粹是为了训练递归意识。
璀璨。
非递归除了代码简短,也没啥别的优势。
int longestConsecutive(vector<int> &num) {
if(num.size()==0) return 0;
int left,right,maxv=1;
unordered_map<int,int> memo;
for(auto n:num){
left=right=0;
if(memo.find(n)!=memo.end())continue;
if(memo.find(n-1)!=memo.end()) left=memo[n-1];
if(memo.find(n+1)!=memo.end()) right=memo[n+1];
memo[n]=left+right+1;
maxv=max(maxv,memo[n]);
memo[n+right]=memo[n-left]=left+right+1;
}
return maxv;
}