【leetcode】706. 设计哈希映射(design-hashmap)(模拟)[简单]

2023-05-16

链接

https://leetcode-cn.com/problems/design-hashmap/

耗时

解题:13 min
题解:8 min

题意

不使用任何内建的哈希表库设计一个哈希映射(HashMap)。

实现 MyHashMap 类:

  • MyHashMap() 用空映射初始化对象
  • void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。如果 key 已经存在于映射中,则更新其对应的值 value 。
  • int get(int key) 返回特定的 key 所映射的 value ;如果映射中不包含 key 的映射,返回 -1 。
  • void remove(key) 如果映射中存在 key 的映射,则移除 key 和它所对应的 value 。

提示:

  • 0 <= key, value <= 1 0 6 10^6 106
  • 最多调用 1 0 4 10^4 104 次 put、get 和 remove 方法

思路

链地址法:哈希函数 x%base,put() 先在哈希值的链表的里面找,找到更新值,没找到添加一对进去;get() 在哈希值的链表里面找,找到就返回值,否则返回 -1;remove() 在哈希值的链表的里面找,找到就删掉这个位置的元素对,然后直接返回。

时间复杂度: O ( n / b ) O(n/b) O(n/b) 假设均匀分布,n个数据,b个链表中有数据

AC代码

class MyHashMap {
private:
    vector<list<pair<int, int>>> data;
    int base = 769;                                    
public:
    int hash(int x) {
        return x % base;
    }                              
                                        
    /** Initialize your data structure here. */
    MyHashMap() {
        data.resize(base);
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
        int h = hash(key);
        for(auto it = data[h].begin(); it != data[h].end(); ++it) {
            if(it->first == key) {
                it->second = value;
                return ;
            }
        }
        data[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 x : data[h]) {
            if(x.first == key) return x.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 = data[h].begin(); it != data[h].end(); ++it) {
            if(it->first == key) {
                data[h].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);
 */
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【leetcode】706. 设计哈希映射(design-hashmap)(模拟)[简单] 的相关文章

随机推荐