前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode *706. 设计哈希映射

LeetCode *706. 设计哈希映射

作者头像
SakuraTears
发布2022-01-13 14:42:21
2590
发布2022-01-13 14:42:21
举报
文章被收录于专栏:从零开始的Code生活

题目

sFVye9wM9l.png
sFVye9wM9l.png

思路

和上一个题基本一样,把添加一个数改成添加一对pair就行

代码语言:javascript
复制
class MyHashMap {
public:
    vector<list<pair<int, int>>> mp;
    const int base = 769;
    int hash(int key) {
        return key % base;
    }

    /** Initialize your data structure here. */
    MyHashMap() {
        mp = vector<list<pair<int, int>>>(base);
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
        int n = hash(key);
        for (auto it = mp[n].begin(); it != mp[n].end(); it++) {
            if ((*it).first == key) {
                (*it).second = value;
                return;
            }
        }
        mp[n].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 n = hash(key);
        for (auto it = mp[n].begin(); it != mp[n].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 n = hash(key);
        for (auto it = mp[n].begin(); it != mp[n].end(); it++) {
            if ((*it).first == key) {
                mp[n].erase(it);
                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);
 */
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年03月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档