[LeetCode] 128. Longest Consecutive Sequence

来源:互联网 发布:用c语言表白 编辑:程序博客网 时间:2024/05/29 09:23

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

// Union-Find Solutionclass Solution {public:    int longestConsecutive(vector<int>& nums) {        const int N = (int)nums.size();        unordered_map<int, int> revmap;        UnionFind uf(N);        for (int i = 0; i < nums.size(); i++) {            if (revmap.find(nums[i]) != revmap.end())                continue;            revmap[nums[i]] = i;            if (revmap.find(nums[i] + 1) != revmap.end())                uf.Union(i, revmap[nums[i] + 1]);            if (revmap.find(nums[i] - 1) != revmap.end())                uf.Union(i, revmap[nums[i] - 1]);        }        return uf.MaxComponentSize();    }private:    class UnionFind {    public:        UnionFind(int N) : lnk(N), sz(N, 1), MaxSubSize(N != 0 ? 1 : 0) {            for (int i = 0; i < N; i++) lnk[i] = i;        }        bool Connected(int p, int q) {            return Find(p) == Find(q);        }        int Find(int p) {            if (p != lnk[p]) lnk[p] = Find(lnk[p]);            return lnk[p];        }        int MaxComponentSize() {            return MaxSubSize;        }        void Union(int p, int q) {            int proot = Find(p), qroot = Find(q);            if (proot == qroot) return;            if (sz[proot] < sz[qroot]) {                lnk[proot] = qroot;                sz[qroot] += sz[proot];                MaxSubSize = max(MaxSubSize, sz[qroot]);            } else {                lnk[qroot] = proot;                sz[proot] += sz[qroot];                MaxSubSize = max(MaxSubSize, sz[proot]);            }        }    private:        vector<int> lnk, sz;        int MaxSubSize;    };};

这里写图片描述这里写图片描述

原创粉丝点击