My CPP Solution with hashset


  • 0
    C
    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) 
        {
            if(nums.empty()) return 0;
            
            std::unordered_set<int> numSet;
            for(int n : nums) numSet.insert(n);
            
            int res = 1;
            for(int n : nums)
            {
                auto it = numSet.find(n);
                if(it == numSet.end()) continue;
                numSet.erase(it);
                
                int rightMost = n+1;
                while(true)
                {
                    auto it = numSet.find(rightMost);
                    if(it == numSet.end()) break;
                    numSet.erase(it);
                    rightMost++;
                }
                
                int leftMost = n-1;
                while(true)
                {
                    auto it = numSet.find(leftMost);
                    if(it == numSet.end()) break;
                    numSet.erase(it);
                    leftMost--;
                }
                
                int tmp = rightMost - leftMost - 1;
                if(tmp > res) res = tmp;
            }
            
            return res;
        }
    };
    

Log in to reply
 

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