Simple 12-line fast c++


  • 1
    M
    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            unordered_set<int> s(nums.begin(), nums.end());
            int ans=0;
            
            while (!s.empty()) {
                int val = *s.begin(), k=val+1, len=1;
                s.erase(val);
                
                while (s.find(k)!=s.end())
                    ++len, s.erase(k++);
                
                k=val-1;
                while (s.find(k)!=s.end())
                    ++len, s.erase(k--);
                
                ans=max(ans, len);
            }
            return ans;
        }
    };

Log in to reply
 

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