zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    tp5 -- 微信公众号支付
    tp5对接支付宝支付简单集成
    tp5 -- 腾讯云cos简单使用
    PHP 递归无限极下级
    PHP 头部utf-8
    ThinkPHP5.0-多语言切换
    MySQL插入SQL语句后在phpmyadmin中注释显示乱码
    C#中练级orcle数据查询
    sql中递归查询
    sql server数据类型与其他数据库数据类型对应关系
  • 原文地址:https://www.cnblogs.com/xgbt/p/13057427.html
Copyright © 2011-2022 走看看