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

在这里插入图片描述
代码思路
可以使用链地址法解决冲突。

代码

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值