leetcode 706. Design HashMap (设计哈希表)C语言

题目链接 https://leetcode.com/problems/design-hashmap/

题目描述

 不适用自带的哈希表创建一个哈希表。

确切的说,你的设计应该包含以下功能。

  • put(key, value) :插入 (key, value) 键值对进入哈希表. 如果值已经在哈希表中存在, 更新这个值.
  • get(key): 返回根据key找到的值, 如果没有则返回-1.
  • remove(key) : 如果哈希表中包含这个值,则删除这个值.

样例

MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);          
hashMap.put(2, 2);         
hashMap.get(1);            // returns 1
hashMap.get(3);            // returns -1 (not found)
hashMap.put(2, 1);          // update the existing value
hashMap.get(2);            // returns 1 
hashMap.remove(2);          // remove the mapping for 2
hashMap.get(2);            // returns -1 (not found) 

题目思路

 使用平方探测法创建一个哈希表,注意哈希表的大小应该为10000的两倍,因为当表的一半以上被填满时,之后未必能插入成功。

代码

#define KEY_MOD 21000

typedef struct node{
    int key;
    int val;
}node;


typedef struct {
    node *list;
} MyHashMap;

/** Initialize your data structure here. */

MyHashMap* myHashMapCreate() {
    MyHashMap *table = malloc(sizeof(MyHashMap));
    table->list = malloc(sizeof(node)*KEY_MOD);
    for(int i=0;i<KEY_MOD;i++)
    {
        table->list[i].key = -1;
        table->list[i].val = -1;
    }
    return table;
}
int myHashMapGet(MyHashMap* obj, int key) ;
/** value will always be non-negative. */
void myHashMapPut(MyHashMap* obj, int key, int value) {
    if(myHashMapGet(obj,key)!=-1)
    {
        myHashMapRemove(obj,key);
    }
    int k = key % KEY_MOD;
    int count = 1;
    while(obj->list[k].key != -1)
    {
        k += 2*count -1;
        count++;
    }
    obj->list[k].key = key;
    obj->list[k].val = value;
    
}

/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int myHashMapGet(MyHashMap* obj, int key) {
    for(int i=0;i<KEY_MOD;i++)
    {
        if(obj->list[i].key == key){
            return obj->list[i].val;
        }
    }
    return -1;
}

/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void myHashMapRemove(MyHashMap* obj, int key) {
    for(int i=0;i<KEY_MOD;i++)
    {
        if(obj->list[i].key == key)
        {
            obj->list[i].key = -1;
            obj->list[i].val = -1;
            return ;
        }
    }
}

void myHashMapFree(MyHashMap* obj) {
    free(obj->list);
    free(obj);

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值