-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesign-hashset.cpp
More file actions
65 lines (55 loc) · 1.64 KB
/
Copy pathdesign-hashset.cpp
File metadata and controls
65 lines (55 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// Created by darion.yaphet on 2025/5/3.
//
#include <vector>
#include <list>
using namespace std;
// https://leetcode.cn/problems/design-hashset/
// 使用一个固定大小的数组作为桶(buckets),每个桶存储一个链表。
// 通过哈希函数将键值映射到数组中的某个桶。
// 如果发生哈希冲突(不同的键映射到同一个桶),则在该桶中使用链表存储所有冲突的键。
class MyHashSet {
private:
static const int BUCKET_SIZE = 1000; // 哈希表的桶数量
vector<list<int> > buckets; // 每个桶是一个链表
// 哈希函数:将 key 映射到桶的索引
int hash(int key) {
return key % BUCKET_SIZE;
}
public:
MyHashSet() : buckets(BUCKET_SIZE) {
}
void add(int key) {
int index = hash(key);
auto &bucket = buckets[index];
// 如果 key 已经存在,则不插入
for (int num: bucket) {
if (num == key) {
return;
}
}
bucket.push_back(key); // 插入 key 到链表末尾
}
void remove(int key) {
int index = hash(key);
auto &bucket = buckets[index];
// 查找并删除 key
for (auto it = bucket.begin(); it != bucket.end(); ++it) {
if (*it == key) {
bucket.erase(it);
return;
}
}
}
bool contains(int key) {
int index = hash(key);
auto &bucket = buckets[index];
// 在链表中查找 key
for (int num: bucket) {
if (num == key) {
return true;
}
}
return false;
}
};