每天一道Code 706. 设计哈希映射

tech2022-07-08  163

代码思路 可以使用链地址法解决冲突。

代码

struct Node{ int key; int val; Node* next; Node(int _key,int _val): key(_key),val(_val),next(NULL) {} }; class MyHashMap { public: /** Initialize your data structure here. */ const int mod = 2001; //一般是用素数 vector<Node*> v; //哈希 MyHashMap() { v = vector<Node*> (mod+1,new Node(-1,-1)); //初始化 } /** value will always be non-negative. */ void put(int key, int value) { //插入 int hash_key = key%mod; Node *head = v[hash_key]; while(head->next){ if(head->next->key == key){ //原本键值存在则更新 head->next->val = value; return ; } head = head->next; } head->next = new Node(key,value); //没有则直接插入在尾部 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 hash_key = key%mod; Node *head = v[hash_key]->next; while(head){ if(head->key == key) return head->val; //找到则返回该值 head = head->next; } return -1; //未查找到则返回-1 } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ void remove(int key) { //删除 int hash_key = key%mod; Node *head = v[hash_key]; while(head){ if(head->key == key) { //查找到后,用-1代替删除 head->val = -1; return ; } head = head->next; } return ; } }; /** * Your MyHashMap object will be instantiated and called as such: * MyHashMap* obj = new MyHashMap(); * obj->put(key,value); * int param_2 = obj->get(key); * obj->remove(key); */
最新回复(0)