力扣热题100——哈希表
哈希表
存键值对:map[键] = 值; / set.insert(元素);
查存在性:map.count(键) / set.count(元素)
- 基础存储与查询(键值对映射)
- 公式化思路:哈希表<键类型, 值类型> 表; → 存储 {键:值} 对,通过键快速查值
- 场景:统计元素出现次数(键存元素,值存次数 )、记录元素与下标映射(如两数之和 )
unordered_map<int, int> countMap;
for (int num : nums) {countMap[num]++; // 键num对应的值+1,无则默认0后+1
}
- 存在性判断(集合特性)
- 公式化思路:unordered_set<类型> 集合; → 用集合存储元素,通过 count/contains判断存在性
- 场景:去重、快速判断元素是否出现(如缺失正整数问题辅助判断 )
unordered_set<int> existSet(nums.begin(), nums.end());
for (int i = 1; ; i++) {if (!existSet.count(i)) { // 不存在则返回return i;}
}
两数之和

class Solution {
public:vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int,int> numsmap;for(int i=0;i<nums.size();i++){int result=target-nums[i];if(numsmap.count(result)){return {numsmap[result],i};}numsmap[nums[i]]=i;}return {};}
};
字母异位词分组

#include <vector> // 引入vector容器头文件,用于存储动态数组(如字符串列表、结果分组)
#include <string> // 引入string头文件,用于处理字符串操作
#include <unordered_map> // 引入unordered_map头文件,用于创建哈希表(键值对存储)
#include <algorithm> // 引入algorithm头文件,用于调用sort排序函数using namespace std; // 使用std命名空间,避免在代码中重复写"std::"前缀class Solution { // 定义Solution类,用于封装解题方法
public: // 公共成员函数,外部可直接调用// 函数定义:接收字符串数组strs,返回分组后的字符串二维数组vector<vector<string>> groupAnagrams(vector<string>& strs) {// 创建哈希表:键为排序后的字符串(用于标识异位ram组),值为该组所有原字符串unordered_map<string, vector<string>> map;// 遍历输入的字符串数组中的每个字符串for (string str : strs) {string key = str; // 复制当前字符串作为临时变量keysort(key.begin(), key.end()); // 对key进行排序(异位词排序后结果相同)map[key].push_back(str); // 将原字符串str放入key对应的分组中}// 创建结果容器,用于存储最终的分组结果vector<vector<string>> result;// 遍历哈希表,将每个分组(哈希表的值)放入结果容器for (auto& pair : map) {result.push_back(pair.second); // pair.second是哈希表中每个键对应的字符串数组}return result; // 返回最终的分组结果}
};
最长连续序列

#include <vector> // 引入vector容器头文件,用于处理动态数组
#include <unordered_set> // 引入unordered_set头文件,用于快速查找和去重
#include <algorithm> // 引入algorithm头文件,用于调用max函数
using namespace std; // 使用std命名空间,简化代码书写class Solution { // 定义Solution类,封装解题方法
public: // 公共成员函数,外部可直接调用// 函数定义:接收整数数组nums,返回最长连续序列的长度int longestConsecutive(vector<int>& nums) {// 1. 将数组元素存入unordered_set,实现去重和O(1)时间复杂度的查找unordered_set<int> numSet(nums.begin(), nums.end());// 2. 初始化最大长度为0,用于记录最长连续序列的长度int maxLen = 0;// 3. 遍历集合中的每个元素(已去重,避免重复处理相同元素)for (int num : numSet) {// 4. 判断当前元素是否为连续序列的起点:// 只有当num-1不存在于集合中时,num才是序列的起点(避免重复计算序列)if (!numSet.count(num - 1)) {// 5. 以当前元素为起点,初始化当前序列的长度为1(至少包含自身)int currentNum = num;int currentLen = 1;// 6. 循环查找后续连续元素:只要currentNum+1存在,就延长序列while (numSet.count(currentNum + 1)) {currentNum++; // 移动到下一个连续元素currentLen++; // 序列长度+1}// 7. 更新最大长度:取当前序列长度和历史最大长度的较大值maxLen = max(maxLen, currentLen);}}// 8. 返回最长连续序列的长度return maxLen;}
};
