LeetCode - Map Sum Pairs

本文介绍了两种实现MapSum数据结构的方法。第一种使用unordered_map来高效处理字符串键的插入和求和操作,第二种则利用map进行键值对的管理及前缀匹配计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解法一:unordered_map<string, pair<int,int>>

class MapSum {
public:
    /** Initialize your data structure here. */
    MapSum() {
        
    }
    
    void insert(string key, int val) {
        int diff = val-m[key].first, n=key.size();
        m[key].first = val;
        for(int i=n-1;i>0;i--){
            m[key.substr(0,i)].second += diff;
        }   
    }
    
    int sum(string prefix) {
        return m[prefix].first + m[prefix].second;
    }
private:
    unordered_map<string, pair<int,int>> m;
};

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

解法二:map<string, int>

class MapSum {
public:
    /** Initialize your data structure here. */
    MapSum() {
        
    }
    
    void insert(string key, int val) {
        m[key] = val;
    }
    
    int sum(string prefix) {
        int n = prefix.size(), res=0;
        for(auto it=m.lower_bound(prefix); it!=m.end();it++){
            if(it->first.substr(0, n)!=prefix) break;
            res += it->second;
        }
        return res;
    }
private:
    map<string, int> m;
};

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值