当前位置:网站首页>LeetCode - 哈希表专题
LeetCode - 哈希表专题
2022-07-28 09:00:00 【工科男小Y吖】
前言
进行 哈希表刷题训练 !
一、简介
为什么
对于数组 a[i] = x,下标 i 只能是在某一段范围内的某一个较小的整数,一个数 n 很大或者是实数或者是字符串时就不很难进行通过数组来进行访问。
是什么
哈希表又称为散列表,是一种可以通过任意的关键吗(key)直接进行访问的数据结构。
本质就是将一个复杂信息的集合通过哈希函数映射成一个小的范围的集合作为索引。
组成
哈希表由两部分组成,一个是实现的数据结构,通常是链表(不支持索引来访问)、数组(只能支持一个非常小的整数作为下标)。就引出了另一部分组成,哈希函数,通过输入关键码(key),返回哈希表数据结构的索引,通过将任意一个 key(复杂信息数据,大的整数、实数、字符串)经过哈希函数映射成一个简单小的信息(小的整数)。
对外封装为可以通过关键码直接访问的数据结构:hash_table[key] = value;
实际上是在数据结构的哈希函数 hash(key) 位置存储了 value:data_structure[hash(key)] = value,data_structure 为数组或链表。
处理冲突
将一个大的集合映射成一个小的集合会有冲突(碰撞)。
哈希碰撞:两个不同的 key 计算出同样的 Hash 结果。
解决方法:开散列
- Hash 函数依然用于计算数组下标
- 数组的每个位置存储链表的表头指针
- 每个链表存储具有同样 Hash 值对应要存储的值
完整结构图

集合(Set)与映射(Map)
集合与映射是两个用来维护信息的基本数据结构。
集合(set)是一个抽象的概念(一个封装),怎么实现可以通过哈希表也可以通过平衡二叉树来实现,即哈希表和平衡二叉树是内部实现。
- 集合用来存储不重复的元素
- 有序集合一般用平衡二叉树来实现,时间复杂度为 O(logN)
- 无序集合一般用哈希表来实现,时间复杂度位 O(1)
映射(map)也是一个抽象的概念(一个封装),怎么实现可以通过哈希表也可以通过平衡二叉树来实现,即哈希表和平衡二叉树是内部实现。
- 用来存储不重复的键值对(key-value 对)
- 有序集合,遍历时按照 key 大小排列,一般用平衡二叉树来实现,时间复杂度为 O(logN)
- 无序集合一般用哈希表来实现,时间复杂度位 O(1)
二、刷题
LeetCode 1. 两数之和
LeetCode 1. 两数之和原题链接
思路:
枚举两个的需要先想下是否需要保持顺序,本题以任意顺序返回则 nums[i]+nums[j] 与 nums[j]+nums[i] 没有区别,则自己加一个 j < i 这样的条件便于维护。
代码剖析:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
/* for every num search if (target-number) in nums(除去num) */
// j < i
/* 整体思路: for i = 0~n-1 search if (target - nums[i]) exists in nums[0,i-1] nums[0,i-1]可以用哈希表来维护 */
// 时间复杂度位 O(n)
int n = nums.size();
unordered_map<int, int> val_to_index;
// 不等于尾部,就是找到了,表示存在
for (int i = 0; i < n; i ++) {
if (val_to_index.find(target - nums[i]) != val_to_index.end()) {
return {
val_to_index[target - nums[i]], i};
}
// i每次循环一次,nums[0, i-1]也需要多一个数
// 边循环i,变插入
// 本质是在i之前查找,防止查到i本身
val_to_index[nums[i]] = i;
}
return {
};
}
};
LeetCode 1748. 唯一元素的和原题链接
class Solution {
public:
int sumOfUnique(vector<int>& nums) {
int sum = 0;
vector<int> heap(105, 0);
for (auto num : nums) heap[num] ++;
for (auto num : nums) {
if (heap[num] == 1)
sum += num;
}
return sum;
}
};
LeetCode 387. 字符串中的第一个唯一字符原题链接
class Solution {
public:
int firstUniqChar(string s) {
vector<int> heap(26, 0);
for (auto c : s) heap[c - 'a'] ++;
for (int i = 0; i < s.size(); i ++) {
if (heap[s[i] - 'a'] == 1)
return i;
}
return -1;
}
};
LeetCode 1941. 检查是否所有字符出现次数相同原题链接
class Solution {
public:
bool areOccurrencesEqual(string s) {
vector<int> heap(26, 0);
for (auto c : s) heap[c - 'a'] ++;
int v = heap[s[0] - 'a'];
for (int i = 0; i < 26; i ++) {
if (heap[i] > 0 && heap[i] != v)
return false;
}
return true;
}
};
LeetCode 448. 找到所有数组中消失的数字原题链接
- 没有空间限制的情况下:开一个长度为
n的heap数组用来标记1-n每个数是否出现过,遍历整个nums数组,标记一下所有出现过的数;之后再从1-n遍历heap数组将没有出现过的数输出; - O(1) 的空间复杂度:对原数组进行修改,如果
x出现过,将a[x]变成-a[x](标记),统计没有改变数的数量;
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
for (auto x : nums) {
x = abs(x);
if (nums[x - 1] > 0) nums[x - 1] *= -1; // 没有标记过,进行标记
}
vector<int> ret;
for (int i = 0; i < nums.size(); i ++) {
if (nums[i] > 0)
ret.push_back(i + 1);
}
return ret;
}
};
LeetCode 1512. 好数对的数目原题链接
class Solution {
public:
int numIdenticalPairs(vector<int>& nums) {
vector<int> heap(105, 0);
int ans = 0;
for (int i = 0; i < nums.size(); i ++) {
ans += heap[nums[i]];
heap[nums[i]] ++;
}
return ans;
}
};
边栏推荐
- Activiti startup error: cannot create poolableconnectionfactory (could not create connection to database server
- Title and answer of work permit for safety management personnel of hazardous chemical business units in 2022
- 【C语言】详解顺序表(SeqList)
- The new mode of 3D panoramic display has become the key to breaking the game
- How promise instance solves hell callback
- 376. Swing sequence [greedy, dynamic planning -----]
- 1.5 merge\rebase\revert\stash\branch
- oracle 创建用户且只有查询权限
- Final keyword and enumeration type
- ECCV 2022 | can be promoted without fine adjustment! Registration based anomaly detection framework for small samples
猜你喜欢

译文推荐 | 调试 BookKeeper 协议 - 无界 Ledger

Promise学习笔记
![[one flower, one world - Professor Zheng Yi - the way of simplicity] interpretable neural network](/img/fd/8ae7c00061491ad78a0fd68b7c21b0.png)
[one flower, one world - Professor Zheng Yi - the way of simplicity] interpretable neural network

使用Xposed对软件进行破解

【C语言】详解顺序表(SeqList)

Regular expressions for positive and negative values

就这么一个简单的校验,80%的程序员却做不到,更不理解!

《我的Vivado实战—单周期CPU指令分析》

ECCV 2022 | 无需微调即可推广!基于配准的少样本异常检测框架

MQTT.js 入门教程:学习笔记
随机推荐
【JVM】JVM表示浮点数
CakePHP 4.4.3 发布,PHP 快速开发框架
JDBC连接数据库
Heuristic merging on tree
2022 examination question bank and simulation examination of crane driver (limited to bridge crane)
[package deployment]
C signed and unsigned byte variables
DN-DETR 论文精度,并解析其模型结构 & 2022年CVPR论文
Title and answer of work permit for safety management personnel of hazardous chemical business units in 2022
[swintransformer source code reading II] window attention and shifted window attention
Informatics Olympiad all in one 1617: circle game | 1875: [13noip improvement group] circle game | Luogu p1965 [noip2013 improvement group] circle game
[autosar-rte] - 3-runnable and its task mapping mapping
VR panoramic shooting helps promote the diversity of B & B
21 day learning challenge - "AUTOSAR from introduction to mastery - practical part"
《数据库系统内 幕》分布式系统
面经-手撕代码
ARouter源码解析(一)
LeetCode(剑指 Offer)- 50. 第一个只出现一次的字符
[vscode] vscode usage
2022 safety officer-b certificate examination simulated 100 questions and answers