【LeetCode刷题笔记-76 706:设计哈希映射】

28 篇文章 0 订阅

题目:
在这里插入图片描述
如果做过昨天的题目的话,今天这题就很简单。

我们知道哈希Map是一个key对应一个value,那么在昨天的基础上使用pair模板去插入这个值就好了。
访问的时候用迭代器的first和second访问
C++代码:(测试从昨天那里扒)

class MyHashMap {
public:
	vector<list<pair<int, int>>> hashmap;
    static const int base = 769;
    static int hash(int key) {
        return key % base;
    }

    /** Initialize your data structure here. */
    MyHashMap():hashmap(base) {

    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
		int h = hash(key);
		for(auto it = hashmap[h].begin();it!=hashmap[h].end();it++){
			if((*it).first == key){
				(*it).second = value;
				return;
			}
		}
		hashmap[h].push_back(make_pair(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) {
		int h = hash(key);
		for(auto it = hashmap[h].begin();it!=hashmap[h].end();it++){
			if((*it).first==key){
				return (*it).second;
			}
		}
		return -1;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
		int h = hash(key);
		for(auto it = hashmap[h].begin();it!=hashmap[h].end();it++){
			if((*it).first==key){
				hashmap[h].erase(it);
				return;
			}
		}
    }
};

多提一句,这个hashmap的初始化大小为769是必要的。因为不这么做的话,系统就会分配给你一个大小。同时,会存在两倍增长的关系,造成额外的开销。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值