实现一个 MapSum 类,支持两个方法,insert 和 sum:
暴力求解
var MapSum = function() {
this.map = new Map();
};
MapSum.prototype.insert = function(key, val) {
this.map.set(key, val);
};
MapSum.prototype.sum = function(prefix) {
let res = 0;
for (const s of this.map.keys()) {
if (s.startsWith(prefix)) {
res += this.map.get(s);
}
}
return res;
};
代码实现
var MapSum = function() {
this.map = new Map();
this.prefixmap = new Map();
};
MapSum.prototype.insert = function(key, val) {
const delta = val - (this.map.get(key) || 0);
this.map.set(key, val);
for (let i = 1; i <= key.length; ++i) {
const currprefix = key.substring(0, i);
this.prefixmap.set(currprefix, (this.prefixmap.get(currprefix) || 0) + delta);
}
};
MapSum.prototype.sum = function(prefix) {
return this.prefixmap.get(prefix) || 0;
};