Easy C++ Code


  • 1
    G
        int longestConsecutive(vector<int>& nums) {
            unordered_map<int, int> lengths;
            int max_len = 0;
            for (auto n : nums) {
                if (lengths.count(n) == 0) {
                    int left_len = lengths.count(n - 1) != 0 ? lengths[n - 1] : 0;
                    int right_len = lengths.count(n + 1) != 0 ? lengths[n + 1] : 0;
                    lengths[n] = 1 + left_len + right_len;
                    max_len = max(lengths[n], max_len);
                    lengths[n + right_len] = lengths[n];
                    lengths[n - left_len] = lengths[n];
                }
            }
            return max_len;
        }
    

Log in to reply
 

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