16 ms 94.26% C++ solution.


  • 0
    R

    each element is guaranteed to be accessed only once.

    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            unordered_set<int> s(nums.begin(), nums.end());
            int res = 1;
            while(!s.empty()){
                auto it = s.begin();
                int cur = *it;
                s.erase(it);
                int prev = cur - 1;
                int next = cur + 1;
                int cnt = 1;
                while((it = s.find(prev)) != s.end()){
                    prev--;
                    s.erase(it);
                    cnt++;
                }
                while((it = s.find(next)) != s.end()){
                    next++;
                    s.erase(it);
                    cnt++;
                }
                res = max(res, cnt);
            }
            return res;
        }
    };
    

  • 0
    S

    An issue : before trying to +1(next) or -1(prev) from cur, check the if it would overflow or underflow.


  • 0
    R

    @s510702 why do you have to check it?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.