[leetcode] Longest Consecutive Sequence

Longest Consecutive Sequence

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        unordered_map<int,bool> used;
        
        for(auto i:num){
            used[i]=false;
        }
        
        int longest=0;
        
        for(auto i:num){
            if(used[i]){//i已经标记过
                continue;
            }
            int length=1;
            used[i]=true;//标记i
            
            for(int j=i+1;used.find(j)!=used.end();++j){//找比i大的
                used[j]=true;
                length++;
            }
            
            for(int j=i-1;used.find(j)!=used.end();--j){//找比i小的
                used[j]=true;
                length++;
            }
            
            longest=max(longest,length);
        }
        return longest;
    }
};


你可能感兴趣的:([leetcode] Longest Consecutive Sequence)