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

 

posted @ 2018-05-20 14:34  JTechRoad  阅读(83)  评论(0编辑  收藏  举报