首页 > 其他分享 >「LeetCode Top100」之哈希篇

「LeetCode Top100」之哈希篇

时间:2024-08-04 15:16:33浏览次数:7  
标签:num int vector mp 哈希 return Top100 LeetCode

1. 两数之和

题目链接:https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked
解题状态:通过
标签:数组哈希表

思路:

通过创建一个哈希表来保存数组中的元素,每当遍历一个元素时,若哈希表中不存在另一个与之相加为目标值的元素,就将元素插入到哈希表中。

代码:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> num;
        for(int i = 0; i < nums.size(); ++i) {
            auto iter = num.find(target - nums[i]);
            if(iter != num.end()) {
                return {iter->second, i};
            }
            num[nums[i]] = i;
        }
        return {};
    }
};

49. 字母异位词分组

题目链接:https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked
解题状态:个人思路无法实现,看题解通过!
标签:数组哈希表字符串排序

思路一:

使用unordered_map

由于异位词中的字母是相同的且个数也是相同的,首先将字符串中每个数组内部排序,获得唯一的排序,然后使用map来存储当前唯一排序对应的字符串,最后输出map中的字符串即可。

代码一:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> mp;
        for(string &str : strs) {
            string key = str;
            sort(key.begin(), key.end());
            mp[key].emplace_back(str);
        }
        vector<vector<string>> res;
        for(auto it = mp.begin(); it != mp.end(); ++it) {
            res.emplace_back(it->second);
        }
        return res;
    }
};

思路二:

使用哈希表,官方题解中将字符串中每个字母出现的次数使用字符串表示,作为哈希表的键。但是代码写的真是一言难尽,根本不想看。

代码二:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        // 自定义对 array<int, 26> 类型的哈希函数
        auto arrayHash = [fn = hash<int>{}] (const array<int, 26>& arr) -> size_t {
            return accumulate(arr.begin(), arr.end(), 0u, [&](size_t acc, int num) {
                return (acc << 1) ^ fn(num);
            });
        };

        unordered_map<array<int, 26>, vector<string>, decltype(arrayHash)> mp(0, arrayHash);
        for (string& str: strs) {
            array<int, 26> counts{};
            int length = str.length();
            for (int i = 0; i < length; ++i) {
                counts[str[i] - 'a'] ++;
            }
            mp[counts].emplace_back(str);
        }
        vector<vector<string>> ans;
        for (auto it = mp.begin(); it != mp.end(); ++it) {
            ans.emplace_back(it->second);
        }
        return ans;
    }
};

128. 最长连续序列

题目链接:https://leetcode.cn/problems/longest-consecutive-sequence/description/?envType=study-plan-v2&envId=top-100-liked
解题状态:个人思路无法实现,看题解通过!
标签:并查集数组哈希表

思路:

使用哈希表来存储序列中的所有元素,然后遍历每个元素,先判断当前元素的前一个数值是否存在这个哈希表中,若不存在则表示当前元素是第一个连续元素,接着遍历是否包含下一个数值,最后返回最长的连续序列。

代码:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> num_set;
        for(auto &num : nums) num_set.insert(num);
        int longStreak = 0;
        for(auto &num : num_set) {
            if(!num_set.count(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;
                while(num_set.count(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }
                longStreak = max(longStreak, currentStreak);
            }
        }
        return longStreak;
    }
};

标签:num,int,vector,mp,哈希,return,Top100,LeetCode
From: https://www.cnblogs.com/frontpen/p/18340535

相关文章

  • LeetCode 1387. Sort Integers by The Power Value
    原题链接在这里:https://leetcode.com/problems/sort-integers-by-the-power-value/description/题目:Thepowerofaninteger x isdefinedasthenumberofstepsneededtotransform x into 1 usingthefollowingsteps:if x iseventhen x=x/2if x is......
  • 【leetcode详解】另一棵树的子树 (C++递归:思路精析&& 过程反思)
    思路详解:总体框架:对root树进行先序遍历,如果当前结点(记为cur)的值和subRoot的根节点值相等时,就开始判断 以cur为根节点的树和子树是否结构一样?如何判断两棵树是否结构完全相同?分析:一提到“树”结构,很容易想到在(先/中/后序)遍历上做文章,请教了AI后笔者得知,如果两棵树......
  • leetcode数论(2521. 数组乘积中的不同质因数数目)
    前言经过前期的基础训练以及部分实战练习,粗略掌握了各种题型的解题思路。现阶段开始专项练习。数论包含最大公约数(>=2个数)、最大公约数性质、最小公倍数、区间范围质因素计数(最下间隔)、质因素分解、判断质数、平方根、立方根、互质、同余等等。描述给你一个正整数数组......
  • Leetcode 第 135 场双周赛题解
    Leetcode第135场双周赛题解Leetcode第135场双周赛题解题目1:3222.求出硬币游戏的赢家思路代码复杂度分析题目2:3223.操作后字符串的最短长度思路代码复杂度分析题目3:3224.使差值相等的最少数组改动次数思路代码复杂度分析题目4:思路代码复杂度分析Leetcode......
  • leetcode 021:删除链表的倒数第 N 个结点
    LCR021.删除链表的倒数第N个结点给定一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。示例1:输入:head=[1,2,3,4,5],n=2输出:[1,2,3,5]示例2:输入:head=[1],n=1输出:[]示例3:输入:head=[1,2],n=1输出:[1]structListNode*removeNthF......
  • LeetCode | 160 Intersection of two linkedlists
    https://github.com/dolphinmind/datastructure/tree/datastructure-linkedlist分析判断两个链表是否相交,转换成了双指针相遇的问题。还是那句话,双指针的本质是遍历,走的路其实一样/***解决两个链接不相交而陷入无限循环的情况*初......
  • 哈希
    前置芝士:字符串常用方法推荐文章:花的哈希基础介绍其中讲了无错哈希和多重哈希,但没讲如何\(O(1)\)求出子串哈希值。这里把字符串\(s\)看成\(p\)进制数,使用自然溢出法。技巧:子串哈希我们可以用\(O(n)\)的时间预处理出所有前缀的hash值,然后可以\(O(1)\)求出子串哈希......
  • 【leetcode详解】正方形中的最多点数【中等】(C++思路精析)
    思路精析:自定义结构体解读:一个点是否在题给正方形中,只取决于其横纵坐标的最大值,记为dis沟通二位数组points和字符串s的桥梁,就是这个点的序号,记为idx由此自定义结构体,储存dis和idx//其中booloperator部分的功能:重载小于操作符“<”,使sort(vc.begin(),vc.end());按dis......
  • 代码随想录算法训练营Day18 | Leetcode 530 二叉搜索树的最小绝对差 Leetcode 236 二
    前言今天有一道题目没写,二叉搜索树中的众数,有点太难理解了,先放一放。Leetcode530二叉搜索树的最小绝对差题目链接:530.二叉搜索树的最小绝对差-力扣(LeetCode)代码随想录题解:代码随想录(programmercarl.com)思路:二叉搜索树的性质是中序遍历为升序的,所以我们想找最小绝......
  • LeetCode面试150——238除自身以外数组的乘积
    题目难度:中等默认优化目标:最小化平均时间复杂度。Python默认为Python3。目录1题目描述2题目解析3算法原理及代码实现3.1左右乘积列表参考文献1题目描述给你一个整数数组nums,返回数组answer,其中answer[i]等于nums中除nums[i]之外其余各元素的乘积......