难度简单79
不使用任何内建的哈希表库设计一个哈希集合
具体地说,你的设计应该包含以下的功能
add(value):向哈希集合中插入一个值。contains(value):返回哈希集合中是否存在这个值。remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
示例:MyHashSet hashSet = new MyHashSet(); hashSet.add(1); hashSet.add(2); hashSet.contains(1); // 返回 true hashSet.contains(3); // 返回 false (未找到) hashSet.add(2); hashSet.contains(2); // 返回 true hashSet.remove(2); hashSet.contains(2); // 返回 false (已经被删除)
注意:
- 所有的值都在
[0, 1000000]的范围内。- 操作的总数目在
[1, 10000]范围内。- 不要使用内建的哈希集合库。
HashSet 的实现两个关键点:哈希函数和冲突处理。
哈希函数通常用的是地址存储法。hash = key % len;
冲突处理方法常用的有:单链接法、开放地址法等
我这里使用的是单链接法:相同散列值,放到链表里,每个节点独立。
class MyHashSet {
vector<ListNode*> hashSet;
int len = 1e4;
public:
/** Initialize your data structure here. */
MyHashSet() {
hashSet = vector<ListNode*>(len, new ListNode(-1));
}
void add(int key) {
int hash = key % len;
ListNode* tmp = hashSet[hash];
if(tmp->val != -1){
while(tmp){
if(tmp->val == key){
return;
}
if(!(tmp->next)){
ListNode* node = new ListNode(key);
tmp->next = node;
return;
}
tmp = tmp->next;
}
}else{
tmp->val = key;
return;
}
}
void remove(int key) {
int hash = key % len;
ListNode* tmp = hashSet[hash];
if(tmp->val != -1){
while(tmp){
if(tmp->val == key){
tmp->val = -1;
return;
}
tmp = tmp->next;
}
}
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
int hash = key % len;
ListNode* tmp = hashSet[hash];
while(tmp){
if(tmp->val == key){
return true;
}
tmp = tmp->next;
}
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);
*/
本文介绍了一种使用单链接法处理哈希冲突的方法来设计一个哈希集合。通过自定义哈希函数和链表结构,实现了添加、删除和查找元素的基本操作。在哈希集合中,当哈希值相同时,元素被添加到链表中。这种方法适用于值范围在[0,1000000]且操作次数在[1,10000]的场景。

1677

被折叠的 条评论
为什么被折叠?



