Longest Consecutive Sequence (C++实现)

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;
    }
};
 

 

欢迎关注微信公众号——计算机视觉:

你可能感兴趣的:(sequence)