题目链接 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);
}