LeetCode - Map Sum Pairs

解法一: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);
 */

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/89081994