-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapSumPairs.cpp
More file actions
35 lines (29 loc) · 758 Bytes
/
mapSumPairs.cpp
File metadata and controls
35 lines (29 loc) · 758 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Source: https://leetcode.com/problems/map-sum-pairs/
// Author: Miao Zhang
// Date: 2021-02-28
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
}
void insert(string key, int val) {
int inc = val;
if (vals_.count(key)) inc -= vals_[key];
vals_[key] = val;
for (int i = 1; i <= key.size(); i++) {
sums_[key.substr(0, i)] += inc;
}
}
int sum(string prefix) {
return sums_[prefix];
}
private:
unordered_map<string, int> vals_;
unordered_map<string, int> sums_;
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/