Leetcode705. 設計哈希集合 (哈希,鏈地址法)

鏈接: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);
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章