Add cpp codes for the chapter

computational complexity, sorting, searching.
This commit is contained in:
Yudong Jin
2022-11-27 04:20:30 +08:00
parent 431a0f6caf
commit 19a4ccd86a
32 changed files with 1362 additions and 52 deletions

View File

@@ -4,7 +4,7 @@ comments: true
# 哈希查找
!!! question
!!! question
在数据量很大时,「线性查找」太慢;而「二分查找」要求数据必须是有序的,并且只能在数组中应用。那么是否有方法可以同时避免上述缺点呢?答案是肯定的,此方法被称为「哈希查找」。
@@ -27,6 +27,19 @@ comments: true
}
```
=== "C++"
```cpp title="hashing_search.cpp"
/* 哈希查找(数组) */
int hashingSearch(unordered_map<int, int> map, int target) {
// 哈希表的 key: 目标元素value: 索引
// 若哈希表中无此 key ,返回 -1
if (map.find(target) == map.end())
return -1;
return map[target];
}
```
再比如,如果我们想要给定一个目标结点值 `target` ,获取对应的链表结点对象,那么也可以使用哈希查找实现。
![hash_search_listnode](hashing_search.assets/hash_search_listnode.png)
@@ -37,11 +50,24 @@ comments: true
/* 哈希查找(链表) */
ListNode hashingSearch1(Map<Integer, ListNode> map, int target) {
// 哈希表的 key: 目标结点值value: 结点对象
// 若哈希表中无此 key ,返回 -1
// 若哈希表中无此 key ,返回 null
return map.getOrDefault(target, null);
}
```
=== "C++"
```cpp title="hashing_search.cpp"
/* 哈希查找(链表) */
ListNode* hashingSearch1(unordered_map<int, ListNode*> map, int target) {
// 哈希表的 key: 目标结点值value: 结点对象
// 若哈希表中无此 key ,返回 nullptr
if (map.find(target) == map.end())
return nullptr;
return map[target];
}
```
## 复杂度分析
**时间复杂度:** $O(1)$ ,哈希表的查找操作使用 $O(1)$ 时间。