程式語言 - LeetCode - C++ - 128. Longest Consecutive Sequence



參考資訊:
https://www.cnblogs.com/grandyang/p/4276225.html

題目:


解答:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int ans = 0;
        unordered_set<int> s(nums.begin(), nums.end());

        for (int n : nums) {
            if (!s.count(n)) {
                continue;
            }
            s.erase(n);

            int pre = n - 1;
            int next = n + 1;
            while (s.count(pre)) {
                s.erase(pre--);
            }

            while (s.count(next)) {
                s.erase(next++);
            }

            ans = max(ans, next - pre - 1);
        }

        return ans;
    }
};