> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/algorithm-techniques/hash-table.md).

# 哈希表

### 思想

哈希表通过**哈希函数**把键映射到数组下标，实现平均 O(1) 的插入与查找。冲突用拉链或开放寻址解决。

### C++ 哈希容器

```cpp
#include <unordered_map>
#include <unordered_set>

unordered_map<string, int> mp;   // 平均 O(1)
mp["apple"] = 3;
if (mp.count("apple")) cout << mp["apple"];

unordered_set<int> s;            // 去重集合
s.insert(5);
if (s.count(5)) cout << "存在";
```

### map vs unordered\_map

|     | map      | unordered\_map  |
| --- | -------- | --------------- |
| 底层  | 红黑树      | 哈希表             |
| 有序  | 是        | 否               |
| 复杂度 | O(log n) | 平均 O(1)，最坏 O(n) |

### 手写哈希（取模法）

```cpp
const int MOD = 1000003;
int head[MOD], nxt[N], val[N], tot;

int hashKey(int x) { return (x % MOD + MOD) % MOD; }
```

### 应用

判重、统计出现次数、字符串哈希、构建映射。

### 注意

出题人可能构造数据让 unordered\_map 退化，可加随机种子或改用 map。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/algorithm-techniques/hash-table.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
