Categories
未分类

LeetCode 128. Longest Consecutive Sequence

https://leetcode.com/problems/longest-consecutive-sequence/description/

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> all_nums;
        unordered_map<int, int> unions_rev; // <end_idx, start_idx>
        unordered_map<int, int> unions;     // <start_idx, end_idx>
        int max_length = 0;
        for (int num : nums)
        {
            auto it_r_union = unions_rev.find(num - 1);
            auto it_union = unions.find(num + 1);
            int start_idx = num;
            int end_idx = num;
            if (all_nums.find(num) != all_nums.end())
                continue;
            if (it_union != unions.end() && it_r_union != unions_rev.end())
            {
                // [RRR] num [SSS]
                start_idx = it_r_union->second;
                end_idx = it_union->second;
                unions_rev.erase(it_r_union);
                unions.erase(start_idx);
                unions.erase(it_union);
                unions_rev.erase(end_idx);
            }
            else if (it_union != unions.end())
            {
                // num [SSS]
                end_idx = it_union->second;
                unions.erase(it_union);
                unions_rev.erase(end_idx);
            }
            else if (it_r_union != unions_rev.end())
            {
                // [RRR] num
                start_idx = it_r_union->second;
                unions_rev.erase(it_r_union);
                unions.erase(start_idx);
            }
            unions[start_idx] = end_idx;
            unions_rev[end_idx] = start_idx;
            if (end_idx - start_idx + 1 > max_length)
            {
                max_length = end_idx - start_idx + 1;
            }
            all_nums.insert(num);
        }
        return max_length;
    }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.