Longest Consecutive Sequence(C++実装)

1037 ワード

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        int n = num.size();
        if(n <= 0) return 0;
        if(n == 1) return 1;
        
        sort(num.begin(), num.end());
        
        int maxAll = 1;
        int maxLast = 1;
        
        vector<int>::iterator cit = num.begin();
        vector<int>::iterator lit = cit;
        cit++;
        
        while(cit!=num.end()) {
            int del = *cit - *lit;
            if(del == 0) {
                cit ++;
                lit ++;
                continue;
            }
            if(del == 1) maxLast ++;
            else maxLast = 1;
            maxAll = max(maxAll, maxLast);
            cit ++;
            lit ++;
        }
        
        return maxAll;
    }
};
 

 
微信の公衆番号に注目してください.コンピュータの視覚: