128. Longest Consecutive Sequence

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> s(nums.begin(), nums.end());
        int res = 0;
        while (!s.empty()) {
            int p = *(s.begin());   s.erase(p);
            int cnt = 1;
            for (int i = 1; s.count(p+i); i++) {
                cnt++;
                s.erase(p+i);
            }
            for (int i = -1; s.count(p+i); i--) {
                cnt++;
                s.erase(p+i);
            }
            res = max(res, cnt);
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/9063381.html