持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第30天,点击查看活动详情
一、题目描述:
不使用任何内建的哈希表库设计一个哈希集合(HashSet)。
实现 MyHashSet 类:
- void add(key) 向哈希集合中插入值 key 。
- bool contains(key) 返回哈希集合中是否存在这个值 key 。
- void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
示例:
输入:
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
输出:
[null, null, null, true, false, null, true, null, false]
解释:
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // 返回 True
myHashSet.contains(3); // 返回 False ,(未找到)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // 返回 True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // 返回 False ,(已移除)
提示:
- 0 <= key <= 10^6
- 最多调用 10^4 次 add、remove 和 contains
二、思路分析:
用链式前向星存哈希表即可,用的是拉链法。
用一个映射函数比如说a = ((b % N) + N) % N 来找到对应的哈希桶。
- add:如果能在链表中找到,则直接返回。否则将其用头插法插入哈希表下标为a的桶中;
- remove:如果删除的是链表头,则将链表头后移,否则找到前一个结点的下标i,当前结点的下标j,将其ne[i]设置为ne[j]即可
- contains:遍历链表即可,看是否包括。
三、AC 代码:
class MyHashSet {
public:
/** Initialize your data structure here. */
int h[10010],ne[10010],e[10010],ind, N = 10010;
MyHashSet() {
memset(h,-1,sizeof h); ind = 0;
}
void add(int b) {
if(contains(b)) return;
int a = ((b % N) + N) % N;
e[ind] = b, ne[ind] = h[a], h[a] = ind ++;
}
void remove(int b) {
int a = ((b % N) + N) % N;
if(h[a] != -1 && b == e[h[a]]){
h[a] = ne[h[a]];
return;
}
int pre;
for(int i = h[a]; i != -1; i = ne[i]){
int to = e[i];
if(to == b){
int next = ne[i];
ne[pre] = next;
return;
}
pre = i;
}
}
/** Returns true if this set contains the specified element */
bool contains(int b) {
int a = ((b % N) + N) % N;
for(int i = h[a]; i != -1; i = ne[i]){
int to = e[i];
if(to == b) return true;
}
return false;
}
};
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet* obj = new MyHashSet();
* obj->add(key);
* obj->remove(key);
* bool param_3 = obj->contains(key);
*/