链接:https://leetcode-cn.com/problems/design-hashset
不使用任何内建的哈希表库设计一个哈希集合
具体地说,你的设计应该包含以下的功能
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]范围内。
不要使用内建的哈希集合库。
/* 思路
使用链地址法
*/
#define HSIZE 100000
typedef struct kv_node {
int v;
struct kv_node *next;
}kv_node_t;
typedef struct {
long hsize;
kv_node_t **arr_list;
} MyHashSet;
/** Initialize your data structure here. */
MyHashSet* myHashSetCreate() {
MyHashSet *mh = (MyHashSet *)calloc(1, sizeof(MyHashSet));
mh->hsize = HSIZE;
mh->arr_list = (kv_node_t **)calloc(mh->hsize, sizeof(kv_node_t *));
int i = 0;
for(i = 0; i < mh->hsize; i++){
mh->arr_list[i] = (kv_node_t *)calloc(1, sizeof(kv_node_t));
mh->arr_list[i]->v = -1;
mh->arr_list[i]->next = NULL;
}
return mh;
}
int hash(MyHashSet* obj, int value){
return value % obj->hsize;
}
void myHashSetAdd(MyHashSet* obj, int key) {
//printf("key[%d]\n", key);
int itor = hash(obj, key);
kv_node_t *p = obj->arr_list[itor];
while(p != NULL){
if(p->v == key){ return; }
if(p->next == NULL){break;}
p = p->next;
}
kv_node_t *new_node = (kv_node_t *)calloc(1, sizeof(kv_node_t));
new_node->v = key;
new_node->next = NULL;
p->next = new_node;
}
void myHashSetRemove(MyHashSet* obj, int key) {
int itor = hash(obj, key);
kv_node_t *p = obj->arr_list[itor];
kv_node_t *f = p;
while(p != NULL){
if(p->v == key){
if(p->next != NULL){
f->next = p->next;
p->next = NULL;
}else{
f->next = NULL;
}
free(p);
return;
}
f = p;
p = p->next;
}
}
/** Returns true if this set contains the specified element */
bool myHashSetContains(MyHashSet* obj, int key) {
int itor = hash(obj, key);
kv_node_t *p = obj->arr_list[itor];
while(p != NULL){
if(p->v == key){ return true; }
p = p->next;
}
return false;
}
void myHashSetFree(MyHashSet* obj) {
int i = 0;
for(i = 0; i < obj->hsize; i++){
free(obj->arr_list[i]);
}
free(obj->arr_list);
free(obj);
}
/**
* Your MyHashSet struct will be instantiated and called as such:
* MyHashSet* obj = myHashSetCreate();
* myHashSetAdd(obj, key);
* myHashSetRemove(obj, key);
* bool param_3 = myHashSetContains(obj, key);
* myHashSetFree(obj);
*/