128. 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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence

1.使用并查集进行计算
mp[x]=x-1表示默认x的father为x-1。然后遍历所给数组进行更新,找到能找到的最远的father,然后计算差值,即为所求答案。

2.更好的find函数

int find(int x){
        return mp.count(x) ? mp[x] = find(mp[x]) : x;
    }

3.map 与 unordered_map
map:

优点:有序性,这是map结构最大的优点,其元素的有序性在很多应用中都会简化很多的操作
缺点: 空间占用率高,因为map内部实现了红黑树,虽然提高了运行效率,但是因为每一个节点都需要额外保存父节点、孩子节点和红/黑性质,使得每一个节点都占用大量的空间
适用:对于那些有顺序要求的问题,用map会更高效一些

unordered_map:
优点: 因为内部实现了哈希表,因此其查找速度非常的快
缺点: 哈希表的建立比较耗费时间
适用:对于查找问题,unordered_map会更加高效一些,因此遇到查找问题,常会考虑一下用unordered_map

class Solution {
public:
    unordered_map <int,int> mp;
    int find(int x){
        return mp.count(x) ? mp[x] = find(mp[x]) : x;
    }
    int longestConsecutive(vector<int>& nums) {
        for (auto x : nums){
            mp[x] = x - 1;
        }
        int ret = 0;
        for (auto x : nums){
            int tmp = find(x-1);
            ret = max(ret,x - tmp);
        }
        return ret;
    }
};
原文地址:https://www.cnblogs.com/xgbt/p/13057427.html