C++ Using unordered_map


  • -1
    Y
    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            int ans=1;
            unordered_map<int,int> dict;
            for(auto i:nums){
                dict[i]=1;
            }
            
            for(int i=0;i<nums.size();i++){
                if(!dict.count(nums[i]))continue;
                int j=1;
                while(dict.count(nums[i]+j)){
                    //dict[nums[i]] is the length of sequence start from nums[i]
                    dict[nums[i]]+=dict[nums[i]+j];
                    //delete the nums after nums[i]
                    dict.erase(nums[i]+j);
                    j++;
                }
                ans=max(ans,dict[nums[i]]);
            }
            return ans;
        }
    };

Log in to reply
 

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