LeetCode: 627.键值映射

64 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第21天,点击查看活动详情

627.键值映射

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ma…

实现一个 MapSum 类,支持两个方法,insert 和 sum:

MapSum() 初始化 MapSum 对象 void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。 int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。

示例:

输入: ["MapSum", "insert", "sum", "insert", "sum"] [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]] 输出: [null, null, 3, null, 5] 解释: MapSum mapSum = new MapSum(); mapSum.insert("apple", 3);
mapSum.sum("ap"); // return 3 (apple = 3) mapSum.insert("app", 2);
mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)

提示:

1 <= key.length, prefix.length <= 50 key 和 prefix 仅由小写英文字母组成 1 <= val <= 1000 最多调用 50 次 insert 和 sum

解法

  • 该题目是一个设计题,键值映射,且需要统计前缀相同的键的值的总和。
  • 解题思路:
    • 哈希表,暴力遍历
    • 哈希表,前缀树

哈希表+暴力法

  • python
class MapSum:

    def __init__(self):
        self.map = {}


    def insert(self, key: str, val: int) -> None:
        self.map[key] = val

    def sum(self, prefix: str) -> int:
        res = 0
        for k, v in self.map.items():
            if k.startswith(prefix):
                res += v
        return res



# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)
  • c++
class MapSum {
private:
    unordered_map<string, int> cnt;

public:
    MapSum() {

    }
    
    void insert(string key, int val) {
        cnt[key] = val;
    }
    
    int sum(string prefix) {
        int res = 0;
        for(auto &[key,val]: cnt)
        {
            if (key.substr(0, prefix.size()) == prefix)
            {
                res += val;
            }
        }
        return res;
    }
};

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum* obj = new MapSum();
 * obj->insert(key,val);
 * int param_2 = obj->sum(prefix);
 */

前缀哈希表 用哈希表存储所有可能前缀的值。当得到一个新的key-val 键值,将 key 的每个前缀 prefix[i] 都在哈希表中进行存储,需要更新每个前缀prefix[i] 对应的值。计算出它对应的值的增加为delta,计算方式如下:

  • 如果键 key 不存在,则此时delta 等于val
  • 如果键key 存在,则此时键key 对应得前缀的值都增加val−map[key],其中 map[key] 表示键key 当前对应的值。
  • 在完成前缀的值改写后,同时要更新键key 对应的值为val。

求sum 时,直接利用哈希表查找给定的前缀对应的值即可。

  • python
class MapSum:
    def __init__(self):
        self.map = {}
        self.prefixmap = {}

    def insert(self, key: str, val: int) -> None:
        delta = val
        if key in self.map:
            delta -= self.map[key]
        self.map[key] = val
        for i in range(len(key)):
            currprefix = key[0:i+1]
            if currprefix in self.prefixmap:
                self.prefixmap[currprefix] += delta
            else:
                self.prefixmap[currprefix] = delta

    def sum(self, prefix: str) -> int:
        if prefix in self.prefixmap:
            return self.prefixmap[prefix]
        else:
            return 0
class MapSum {
public:
    MapSum() {

    }
    
    void insert(string key, int val) {
        int delta = val;
        if (map.count(key)) {
            delta -= map[key];
        }
        map[key] = val;
        for (int i = 1; i <= key.size(); ++i) {
            prefixmap[key.substr(0, i)] += delta;
        }
    }
    
    int sum(string prefix) {
        return prefixmap[prefix];
    }
private:
    unordered_map<string, int> map;
    unordered_map<string, int> prefixmap;
};

复杂度分析

  • 时间复杂度:
    • O(NM)O(NM)
    • O(N2)O(N^2)
  • 空间复杂度:
    • O(NM)O(NM)
    • O(NM)O(NM)

参考