leetcode之 Longest Consecutive Sequence

題目:Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

解題思路

此處撰寫解題思路
map縮點+並查集很經典
把第i-1 和 i連起來
i和i+1 連起來記錄一下每個集合的個數。最大的就是最長鏈。

AC代碼:

class Solution {
public:
    vector<int> fa, sum;
    void init() {
        for (int i = 0; i < fa.size(); ++i) 
            fa[i] = i, sum[i] = 1;
    }
    int Find(int &x) {
        return x == fa[x] ? x : fa[x] = Find(fa[x]); 
    }
    bool Uion(int x, int y) {
        int fx = Find(x), fy = Find(y);
        if (fx == fy)
            return false;
        sum[fx] += sum[fy];
        fa[fy] = fx;
        return true;
    }
    // int max(initializer_list<int> li) {
    //     int &a = *li.begin();
    //     for (auto &i : li)
    //         a = a>i?a:i;
    //     return a;
    // }
    int longestConsecutive(vector<int>& nums) {
        if (nums.empty()) return 0;
        map<int, int>ma;
        fa = sum = vector<int>(nums.size()+1);
        init();
        int tot = 0;
        for (auto &i : nums) {
            if (ma.find(i) != ma.end()) continue;
            ma[i] = tot++;
            if (ma.find(i-1) != ma.end())
                Uion(ma[i-1], ma[i]);
            if (ma.find(i+1) != ma.end())
                Uion(ma[i], ma[i+1]);
        }
        int x = sum[Find(ma[nums[0]])];
        for (auto &i : nums)
            x = max(x, sum[ma[i]]);
        return x;
    }
};

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-consecutive-sequence
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章