1,题目要求
Design a HashMap without using any built-in hash table libraries.
To be specific, your design should include these functions:
设计并实现一个HashMap。
2,题目思路
比较简单的办法,是直接定义vector来实现这样的HashMap,利用vector容器的特性来实现。不过这种办法的效率比较低。(加上前面的cin优化之后会好一些)
而另外一种办法,则是利用自己定义的链表来存储这样的节点,并利用mod运算来减少空间的存储:即创建长度适当的vector,其中的元素类型为Node*类型,即元素类型为单链表类型,在保证搜索效率的基础的上也可以减少空间存储的消耗。而删除元素和添加元素也是用到了链表的特性罢了。
3,程序源码
方法1:(直接利用vector)
static int pr = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class MyHashMap {
public:
/** Initialize your data structure here. */
MyHashMap() {}
/** value will always be non-negative. */
void put(int key, int value) {
HashMap[key] = value;
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int get(int key) {
return HashMap[key];
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
HashMap[key] = -1;
}
private:
vector<int> HashMap = vector<int> (1000001, -1);
};
注:
脑子有点昏了,以为vector<int> HashMap = vector<int> (1000001, -1);
是创建一个二维向量,其实就是简单的一维向量的初始化的定义方式罢了。跟:
vector<int> HashMap (100001, -1);
效果是一样的,但是在类中不能这样直接的进行定义,需要先声明后,再进行初始化,就像上面的代码的方式那样。
方法2:(利用链表)
static int pr = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class MyHashMap {
public:
/** Initialize your data structure here. */
MyHashMap() {
slots = 3333; //减少空间的占用
hm = vector<mapNode*>(slots, NULL);//相当于创建了3333个单链表
}
/** value will always be non-negative. */
void put(int key, int value) {
int slot = key % slots;
for(auto ptr = hm[slot];ptr != NULL;ptr = ptr->next)
{
if(ptr->key == key) //找到了节点,更新值
{
ptr->val = value;
return;
}
}
//没有找到(插入到第一个节点前面)
auto tmp = hm[slot]; //第一个节点
hm[slot] = new mapNode(key, value);
hm[slot]->next = tmp;
return;
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int get(int key) {
int slot = key % slots;
for(auto ptr = hm[slot];ptr != NULL;ptr = ptr->next)
if(ptr->key == key) return ptr->val;
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
int slot = key % slots;
if(hm[slot] == NULL) return;
else if(hm[slot]->key == key)
{
hm[slot] = hm[slot]->next;
return;
}
else
{
for(auto ptr= hm[slot], pre = hm[slot];ptr != NULL;pre = ptr, ptr = ptr->next)
{
if(ptr->key == key)
{
pre->next = ptr->next;
return;
}
}
}
}
private:
struct mapNode {
int key;
int val;
mapNode* next;
mapNode(int k, int v) : key(k), val(v), next(NULL) {};
};
vector<mapNode*> hm;
int slots;
};