Add figures to replace_linear_by_hashing.md

This commit is contained in:
krahets 2023-05-09 00:36:18 +08:00
parent 53ca2144e2
commit fe69f7240d
23 changed files with 85 additions and 80 deletions

View file

@ -1 +1 @@
add_executable(leetcode_two_sum leetcode_two_sum.c)
add_executable(two_sum two_sum.c)

View file

@ -1,5 +1,5 @@
/**
* File: leetcode_two_sum.c
* File: two_sum.c
* Created Time: 2023-01-19
* Author: Reanon (793584285@qq.com)
*/
@ -71,7 +71,7 @@ int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
int main() {
// ======= Test Case =======
int nums[] = {2, 7, 11, 15};
int target = 9;
int target = 13;
// ====== Driver Code ======
int returnSize;
int *res = twoSumBruteForce(nums, sizeof(nums) / sizeof(int), target, &returnSize);

View file

@ -1,3 +1,3 @@
add_executable(hashing_search hashing_search.cpp)
add_executable(leetcode_two_sum leetcode_two_sum.cpp)
add_executable(two_sum two_sum.cpp)
add_executable(linear_search linear_search.cpp)

View file

@ -1,5 +1,5 @@
/**
* File: leetcode_two_sum.cpp
* File: two_sum.cpp
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
@ -38,7 +38,7 @@ vector<int> twoSumHashTable(vector<int> &nums, int target) {
int main() {
// ======= Test Case =======
vector<int> nums = {2, 7, 11, 15};
int target = 9;
int target = 13;
// ====== Driver Code ======
// 方法一

View file

@ -1,12 +1,12 @@
/**
* File: leetcode_two_sum.cs
* File: two_sum.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_searching;
public class leetcode_two_sum {
public class two_sum {
/* 方法一:暴力枚举 */
public static int[] twoSumBruteForce(int[] nums, int target) {
int size = nums.Length;
@ -39,7 +39,7 @@ public class leetcode_two_sum {
public void Test() {
// ======= Test Case =======
int[] nums = { 2, 7, 11, 15 };
int target = 9;
int target = 13;
// ====== Driver Code ======
// 方法一

View file

@ -1,5 +1,5 @@
/**
* File: leetcode_two_sum.dart
* File: two_sum.dart
* Created Time: 2023-2-11
* Author: Jefferson (JeffersonHuang77@gmail.com)
*/
@ -34,7 +34,7 @@ List<int> twoSumHashTable(List<int> nums, int target) {
int main() {
// ======= Test Case =======
List<int> nums = [2, 7, 11, 15];
int target = 9;
int target = 13;
// ====== Driver Code ======
//

View file

@ -1,4 +1,4 @@
// File: leetcode_two_sum.go
// File: two_sum.go
// Created Time: 2022-11-25
// Author: reanon (793584285@qq.com)

View file

@ -1,4 +1,4 @@
// File: leetcode_two_sum_test.go
// File: two_sum_test.go
// Created Time: 2022-11-25
// Author: reanon (793584285@qq.com)
@ -12,7 +12,7 @@ import (
func TestTwoSum(t *testing.T) {
// ======= Test Case =======
nums := []int{2, 7, 11, 15}
target := 9
target := 13
// ====== Driver Code ======
// 方法一:暴力解法

View file

@ -1,5 +1,5 @@
/**
* File: leetcode_two_sum.java
* File: two_sum.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
@ -8,7 +8,7 @@ package chapter_searching;
import java.util.*;
public class leetcode_two_sum {
public class two_sum {
/* 方法一:暴力枚举 */
static int[] twoSumBruteForce(int[] nums, int target) {
int size = nums.length;
@ -40,7 +40,7 @@ public class leetcode_two_sum {
public static void main(String[] args) {
// ======= Test Case =======
int[] nums = { 2, 7, 11, 15 };
int target = 9;
int target = 13;
// ====== Driver Code ======
// 方法一

View file

@ -1,5 +1,5 @@
/**
* File: leetcode_two_sum.js
* File: two_sum.js
* Created Time: 2022-12-15
* Author: gyt95 (gytkwan@gmail.com)
*/
@ -36,7 +36,7 @@ function twoSumHashTable(nums, target) {
/* Driver Code */
// 方法一
const nums = [2, 7, 11, 15],
target = 9;
target = 13;
let res = twoSumBruteForce(nums, target);
console.log('方法一 res = ', res);

View file

@ -1,5 +1,5 @@
"""
File: leetcode_two_sum.py
File: two_sum.py
Created Time: 2022-11-25
Author: Krahets (krahets@163.com)
"""
@ -31,7 +31,7 @@ def two_sum_hash_table(nums: list[int], target: int) -> list[int]:
if __name__ == "__main__":
# ======= Test Case =======
nums = [2, 7, 11, 15]
target = 9
target = 13
# ====== Driver Code ======
# 方法一

View file

@ -19,10 +19,10 @@ path = "chapter_computational_complexity/worst_best_time_complexity.rs"
name = "space_complexity"
path = "chapter_computational_complexity/space_complexity.rs"
# Run Command: cargo run --bin leetcode_two_sum
# Run Command: cargo run --bin two_sum
[[bin]]
name = "leetcode_two_sum"
path = "chapter_computational_complexity/leetcode_two_sum.rs"
name = "two_sum"
path = "chapter_computational_complexity/two_sum.rs"
# Run Command: cargo run --bin array
[[bin]]

View file

@ -1,5 +1,5 @@
/*
* File: leetcode_two_sum.rs
* File: two_sum.rs
* Created Time: 2023-01-14
* Author: xBLACICEx (xBLACKICEx@outlook.com), sjinzh (sjinzh@gmail.com)
*/
@ -39,7 +39,7 @@ pub fn two_sum_hash_table(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
fn main() {
// ======= Test Case =======
let nums = vec![ 2, 7, 11, 15 ];
let target = 9;
let target = 13;
// ====== Driver Code ======
// 方法一

View file

@ -43,7 +43,7 @@ let package = Package(
.executable(name: "graph_bfs", targets: ["graph_bfs"]),
.executable(name: "graph_dfs", targets: ["graph_dfs"]),
// chapter_searching
.executable(name: "leetcode_two_sum", targets: ["leetcode_two_sum"]),
.executable(name: "two_sum", targets: ["two_sum"]),
.executable(name: "linear_search", targets: ["linear_search"]),
.executable(name: "hashing_search", targets: ["hashing_search"]),
// chapter_sorting
@ -104,7 +104,7 @@ let package = Package(
.executableTarget(name: "graph_bfs", dependencies: ["utils", "graph_adjacency_list_target"], path: "chapter_graph", sources: ["graph_bfs.swift"]),
.executableTarget(name: "graph_dfs", dependencies: ["utils", "graph_adjacency_list_target"], path: "chapter_graph", sources: ["graph_dfs.swift"]),
// chapter_searching
.executableTarget(name: "leetcode_two_sum", path: "chapter_searching", sources: ["leetcode_two_sum.swift"]),
.executableTarget(name: "two_sum", path: "chapter_searching", sources: ["two_sum.swift"]),
.executableTarget(name: "linear_search", dependencies: ["utils"], path: "chapter_searching", sources: ["linear_search.swift"]),
.executableTarget(name: "hashing_search", dependencies: ["utils"], path: "chapter_searching", sources: ["hashing_search.swift"]),
// chapter_sorting

View file

@ -1,5 +1,5 @@
/**
* File: leetcode_two_sum.swift
* File: two_sum.swift
* Created Time: 2023-01-03
* Author: nuomi1 (nuomi1@qq.com)
*/
@ -37,7 +37,7 @@ enum LeetcodeTwoSum {
static func main() {
// ======= Test Case =======
let nums = [2, 7, 11, 15]
let target = 9
let target = 13
// ====== Driver Code ======
//
var res = twoSumBruteForce(nums: nums, target: target)

View file

@ -1,5 +1,5 @@
/**
* File: leetcode_two_sum.ts
* File: two_sum.ts
* Created Time: 2022-12-15
* Author: gyt95 (gytkwan@gmail.com)
*/
@ -37,7 +37,7 @@ function twoSumHashTable(nums: number[], target: number): number[] {
/* Driver Code */
// 方法一
const nums = [2, 7, 11, 15],
target = 9;
target = 13;
let res = twoSumBruteForce(nums, target);
console.log('方法一 res = ', res);

View file

@ -52,18 +52,18 @@ pub fn build(b: *std.build.Builder) void {
run_step_space_complexity.dependOn(&run_cmd_space_complexity.step);
// Section: "Space Time Tradeoff"
// Source File: "chapter_computational_complexity/leetcode_two_sum.zig"
// Run Command: zig build run_leetcode_two_sum
const exe_leetcode_two_sum = b.addExecutable("leetcode_two_sum", "chapter_computational_complexity/leetcode_two_sum.zig");
exe_leetcode_two_sum.addPackagePath("include", "include/include.zig");
exe_leetcode_two_sum.setTarget(target);
exe_leetcode_two_sum.setBuildMode(mode);
exe_leetcode_two_sum.install();
const run_cmd_leetcode_two_sum = exe_leetcode_two_sum.run();
run_cmd_leetcode_two_sum.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_leetcode_two_sum.addArgs(args);
const run_step_leetcode_two_sum = b.step("run_leetcode_two_sum", "Run leetcode_two_sum");
run_step_leetcode_two_sum.dependOn(&run_cmd_leetcode_two_sum.step);
// Source File: "chapter_computational_complexity/two_sum.zig"
// Run Command: zig build run_two_sum
const exe_two_sum = b.addExecutable("two_sum", "chapter_computational_complexity/two_sum.zig");
exe_two_sum.addPackagePath("include", "include/include.zig");
exe_two_sum.setTarget(target);
exe_two_sum.setBuildMode(mode);
exe_two_sum.install();
const run_cmd_two_sum = exe_two_sum.run();
run_cmd_two_sum.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_two_sum.addArgs(args);
const run_step_two_sum = b.step("run_two_sum", "Run two_sum");
run_step_two_sum.dependOn(&run_cmd_two_sum.step);
// Section: "Array"
// Source File: "chapter_array_and_linkedlist/array.zig"

View file

@ -1,4 +1,4 @@
// File: leetcode_two_sum.zig
// File: two_sum.zig
// Created Time: 2023-01-07
// Author: sjinzh (sjinzh@gmail.com)

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

View file

@ -1,78 +1,74 @@
# 哈希优化策略
在算法题中,**我们常通过将线性查找替换为哈希查找来降低算法的时间复杂度**。以 LeetCode 全站第一题 [两数之和](https://leetcode.cn/problems/two-sum/) 为例
在算法题中,**我们常通过将线性查找替换为哈希查找来降低算法的时间复杂度**。我们借助一个算法题来加深理解
!!! question "两数之和"
给定一个整数数组 `nums` 和一个整数目标值 `target` ,请你在该数组中找出“和”为目标值 `target` 的那两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
给定一个整数数组 `nums` 和一个整数目标值 `target` ,请在数组中搜索“和”为目标值 `target` 的两个整数,并返回他们在数组中的索引。注意,数组中同一个元素在答案里不能重复出现。返回任意一个解即可。
## 线性查找:以时间换空间
考虑直接遍历所有可能的组合。开启一个两层循环,在每轮中判断两个整数的和是否为 `target` ,若是,则返回它们的索引。
(图)
![线性查找求解两数之和](replace_linear_by_hashing.assets/two_sum_brute_force.png)
=== "Java"
```java title="leetcode_two_sum.java"
[class]{leetcode_two_sum}-[func]{twoSumBruteForce}
```java title="two_sum.java"
[class]{two_sum}-[func]{twoSumBruteForce}
```
=== "C++"
```cpp title="leetcode_two_sum.cpp"
```cpp title="two_sum.cpp"
[class]{}-[func]{twoSumBruteForce}
```
=== "Python"
```python title="leetcode_two_sum.py"
```python title="two_sum.py"
[class]{}-[func]{two_sum_brute_force}
```
=== "Go"
```go title="leetcode_two_sum.go"
```go title="two_sum.go"
[class]{}-[func]{twoSumBruteForce}
```
=== "JavaScript"
```javascript title="leetcode_two_sum.js"
```javascript title="two_sum.js"
[class]{}-[func]{twoSumBruteForce}
```
=== "TypeScript"
```typescript title="leetcode_two_sum.ts"
```typescript title="two_sum.ts"
[class]{}-[func]{twoSumBruteForce}
```
=== "C"
```c title="leetcode_two_sum.c"
```c title="two_sum.c"
[class]{}-[func]{twoSumBruteForce}
```
=== "C#"
```csharp title="leetcode_two_sum.cs"
[class]{leetcode_two_sum}-[func]{twoSumBruteForce}
```csharp title="two_sum.cs"
[class]{two_sum}-[func]{twoSumBruteForce}
```
=== "Swift"
```swift title="leetcode_two_sum.swift"
```swift title="two_sum.swift"
[class]{}-[func]{twoSumBruteForce}
```
=== "Zig"
```zig title="leetcode_two_sum.zig"
```zig title="two_sum.zig"
[class]{}-[func]{twoSumBruteForce}
```
@ -80,52 +76,61 @@
## 哈希查找:以空间换时间
考虑借助一个哈希表,将数组元素和元素索引构建为键值对。循环遍历数组中的每个元素 `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"
```java title="leetcode_two_sum.java"
[class]{leetcode_two_sum}-[func]{twoSumHashTable}
```java title="two_sum.java"
[class]{two_sum}-[func]{twoSumHashTable}
```
=== "C++"
```cpp title="leetcode_two_sum.cpp"
```cpp title="two_sum.cpp"
[class]{}-[func]{twoSumHashTable}
```
=== "Python"
```python title="leetcode_two_sum.py"
```python title="two_sum.py"
[class]{}-[func]{two_sum_hash_table}
```
=== "Go"
```go title="leetcode_two_sum.go"
```go title="two_sum.go"
[class]{}-[func]{twoSumHashTable}
```
=== "JavaScript"
```javascript title="leetcode_two_sum.js"
```javascript title="two_sum.js"
[class]{}-[func]{twoSumHashTable}
```
=== "TypeScript"
```typescript title="leetcode_two_sum.ts"
```typescript title="two_sum.ts"
[class]{}-[func]{twoSumHashTable}
```
=== "C"
```c title="leetcode_two_sum.c"
```c title="two_sum.c"
[class]{hashTable}-[func]{}
[class]{}-[func]{twoSumHashTable}
@ -133,19 +138,19 @@
=== "C#"
```csharp title="leetcode_two_sum.cs"
[class]{leetcode_two_sum}-[func]{twoSumHashTable}
```csharp title="two_sum.cs"
[class]{two_sum}-[func]{twoSumHashTable}
```
=== "Swift"
```swift title="leetcode_two_sum.swift"
```swift title="two_sum.swift"
[class]{}-[func]{twoSumHashTable}
```
=== "Zig"
```zig title="leetcode_two_sum.zig"
```zig title="two_sum.zig"
[class]{}-[func]{twoSumHashTable}
```