不使用任何内建的哈希表库设计一个哈希集合
具体地说,你的设计应该包含以下的功能
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]
范围内。struct Node{
int val;
Node *next;
Node(int val): val(val),next(nullptr){}
};
const int len = 100;
class MyHashSet {
public:
vector<Node*> arr; //本题题点
/** Initialize your data structure here. */
MyHashSet() {
arr = vector<Node*>(len, new Node(-1));
}
void add(int key) {
int haval = key % len;
Node* temp = arr[haval];
if(temp -> val != -1){
while(temp){
if(temp -> val == key) return;
if(!(temp -> next)){
Node *node = new Node(key);
temp -> next = node;
return;
}
temp = temp -> next;
}
}
else{
temp -> val = key;
return;
}
}
void remove(int key) {
int haval = key % len;
Node* temp = arr[haval];
if(temp -> val != -1){
while(temp){
if(temp -> val == key){
temp -> val = -1;
return;
}
temp = temp -> next;
}
}
}
/** Returns true if this set contains the specified element */
bool contains(int key) {
int haval = key % len;
Node* temp = arr[haval];
while(temp){
if(temp -> val == key) return true;
temp = temp -> next;
}
return false;
}
};
作者:youlookdeliciousc
链接:https://leetcode-cn.com/problems/design-hashset/solution/cxiang-xi-ti-jie-by-youlookdeliciousc-18/
来源:力扣(LeetCode)