当前位置:网站首页>Leetcode - hashtable topic
Leetcode - hashtable topic
2022-07-28 09:39:00 【Engineering Male small y acridine】
Preface
Conduct Hash table exercise !
List of articles
One 、 brief introduction
Why?
For arrays a[i] = x, Subscript i It can only be a small integer within a certain range , a number n It is not difficult to access arrays when they are large, real numbers or strings .
What is it?
Hash table is also called hash table , Is it a key that can pass any (key) Data structure for direct access .
The essence is to map a set of complex information into a small range set as an index through a hash function .
form
The hash table consists of two parts , One is the data structure of the implementation , Usually linked list ( Index access is not supported )、 Array ( Only a very small integer can be supported as a subscript ). It leads to another part , hash function , By entering a key (key), Returns the index of the hash table data structure , By placing any one key( Complex information data , Big integers 、 The set of real Numbers 、 character string ) After the hash function mapping into a simple small information ( Small integers ).
Externally encapsulated as a data structure that can be accessed directly through key :hash_table[key] = value;
In fact, it is in the hash function of the data structure hash(key) The location stores value:data_structure[hash(key)] = value,data_structure Array or linked list .
Handling conflicts
Mapping a large set to a small set will have conflicts ( Collision ).
Hash collision : Two different key Calculate the same Hash result .
resolvent : Hash
- Hash The function is still used to calculate the array subscript
- Each position of the array stores the header pointer of the linked list
- Each linked list store has the same Hash The value corresponds to the value to be stored
Complete structure drawing

aggregate (Set) And Mapping (Map)
Set and map are two basic data structures used to maintain information .
aggregate (set) It's an abstract concept ( One package ), How to implement it can be achieved through hash table or balanced binary tree , That is, hash table and balanced binary tree are internal implementations .
- Collections are used to store non repeating elements
- Ordered sets are generally realized by balanced binary trees , The time complexity is O(logN)
- Unordered sets are generally implemented with hash tables , Time complexity bit O(1)
mapping (map) It is also an abstract concept ( One package ), How to implement it can be achieved through hash table or balanced binary tree , That is, hash table and balanced binary tree are internal implementations .
- Used to store non duplicate key value pairs (key-value Yes )
- Ordered set , When traversing, follow key Size arrangement , Generally, balanced binary tree is used to realize , The time complexity is O(logN)
- Unordered sets are generally implemented with hash tables , Time complexity bit O(1)
Two 、 Brush problem
LeetCode 1. Sum of two numbers
LeetCode 1. Sum of two numbers Original link
Ideas :
To enumerate two, first think about whether you need to keep the order , If this question returns in any order nums[i]+nums[j] And nums[j]+nums[i] There is no difference between , Add one by yourself j < i Such conditions are convenient for maintenance .
Code analysis :
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
/* for every num search if (target-number) in nums( remove num) */
// j < i
/* The whole idea : for i = 0~n-1 search if (target - nums[i]) exists in nums[0,i-1] nums[0,i-1] Hash table can be used to maintain */
// Time complexity bit O(n)
int n = nums.size();
unordered_map<int, int> val_to_index;
// Not equal to the tail , Just found , Indicates presence
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 One cycle at a time ,nums[0, i-1] It also needs an extra number
// Edge cycle i, Variable insertion
// In essence i Before finding , Prevent detection i In itself
val_to_index[nums[i]] = i;
}
return {
};
}
};
LeetCode 1748. The sum of the only elements Original link
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. The first unique character in the string Original link
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. Check that all characters appear the same number of times Original link
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. Find all the missing numbers in the array Original link
- Without space constraints : Open a length of
nOfheapArrays are used to mark1-nWhether each number has appeared , Traverse the wholenumsArray , Mark all the numbers that have appeared ; And then from1-nTraverseheapThe array will output numbers that have never appeared ; - O(1) Spatial complexity of : Modify the original array , If
xThere have been , takea[x]become-a[x]( Mark ), Count the number of unchanged numbers ;
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; // Not marked , marked
}
vector<int> ret;
for (int i = 0; i < nums.size(); i ++) {
if (nums[i] > 0)
ret.push_back(i + 1);
}
return ret;
}
};
LeetCode 1512. A good number of pairs Original link
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;
}
};
边栏推荐
- 咸鱼ESP32实例—MQTT 点亮LED
- MySQL中各类型文件详解
- [附下载]推荐几款暴力破解和字典生成的工具
- Final keyword and enumeration type
- Promise实例如何解决地狱回调
- 2022牛客多校第一场补题
- Activiti启报错: Cannot create PoolableConnectionFactory (Could not create connection to database server
- How promise instance solves hell callback
- [solution] error in [eslint] eslint is not a constructor
- 《我的Vivado实战—单周期CPU指令分析》
猜你喜欢

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

What is cross domain? How to solve the cross domain problem?

DN-DETR 论文精度,并解析其模型结构 & 2022年CVPR论文

oracle 创建用户且只有查询权限

opencv安装配置测试

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

Database core system

Introduction to shardingsphere's concept of sub database and sub table (2)

Alibaba cloud server setup and pagoda panel connection

译文推荐 | 调试 BookKeeper 协议 - 无界 Ledger
随机推荐
《PyTorch深度学习实践》第九课多分类问题(手写数字MNIST)
这两套代码有什么区别呢?
【解决】ERROR in [eslint] ESLint is not a constructor
树上启发式合并
Detailed introduction of v-bind instruction
7 C control statements: branches and jumps
Window源码解析(一):与DecorView的那些事
Changes in the relationship between data and application in IT industry
常用工具函数 持续更新
【杂谈】程序员的发展最需要两点能力
MQTT. JS introductory tutorial: learning notes
JDBC connection database
Dn-detr paper accuracy, and analyze its model structure & 2022 CVPR paper
Talk to the father of MySQL: code completion at one time is a good programmer
[autosar-rte] - introduction of 2-component, component and VFB
[JVM] JVM refers to floating point number
【打包部署】
可以伸缩的搜索栏,模仿华为应用市场
MQTT.js 入门教程:学习笔记
Title and answer of work permit for safety management personnel of hazardous chemical business units in 2022