This commit is contained in:
krahets
2023-05-09 00:26:55 +08:00
parent 73b4654ebb
commit 91f5d10c75
2 changed files with 261 additions and 14 deletions
+18 -11
View File
@@ -4,21 +4,19 @@ comments: true
# 12.2.   哈希优化策略
在算法题中,**我们常通过将线性查找替换为哈希查找来降低算法的时间复杂度**。以 LeetCode 全站第一题 [两数之和](https://leetcode.cn/problems/two-sum/) 为例
在算法题中,**我们常通过将线性查找替换为哈希查找来降低算法的时间复杂度**。我们借助一个算法题来加深理解
!!! question "两数之和"
给定一个整数数组 `nums` 和一个整数目标值 `target` ,请你在该数组中找出“和”为目标值 `target`两个整数,并返回它们的数组下标
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
给定一个整数数组 `nums` 和一个整数目标值 `target` ,请数组中搜索“和”为目标值 `target` 的两个整数,并返回他们在数组中的索引。注意,数组中同一个元素在答案里不能重复出现。返回任意一个解即可
## 12.2.1.   线性查找:以时间换空间
考虑直接遍历所有可能的组合。开启一个两层循环,在每轮中判断两个整数的和是否为 `target` ,若是,则返回它们的索引。
(图)
![线性查找求解两数之和](replace_linear_by_hashing.assets/two_sum_brute_force.png)
<p align="center"> Fig. 线性查找求解两数之和 </p>
=== "Java"
@@ -199,12 +197,21 @@ comments: true
## 12.2.2. &nbsp; 哈希查找:以空间换时间
考虑借助一个哈希表,数组元素和元素索引构建为键值对。循环遍历数组中的每个元素 `num` 并执行:
考虑借助一个哈希表,键值对分别为数组元素和元素索引。循环遍历数组,每轮执行:
1. 判断数字 `target - num` 是否在哈希表中,若是则直接返回两个元素的索引;
2. 将元素 `num` 和索引添加进哈希表;
1. 判断数字 `target - nums[i]` 是否在哈希表中,若是则直接返回两个元素的索引;
2. 将键值对 `num[i]` 和索引 `i` 添加进哈希表;
(图)
=== "<1>"
![two_sum_hashtable_step1](replace_linear_by_hashing.assets/two_sum_hashtable_step1.png)
=== "<2>"
![two_sum_hashtable_step2](replace_linear_by_hashing.assets/two_sum_hashtable_step2.png)
=== "<3>"
![two_sum_hashtable_step3](replace_linear_by_hashing.assets/two_sum_hashtable_step3.png)
实现代码如下所示,仅需单层循环即可。
=== "Java"