-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path677_Map Sum Pairs.js
51 lines (45 loc) · 977 Bytes
/
677_Map Sum Pairs.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// https://leetcode.com/problems/map-sum-pairs/description/
/**
* Initialize your data structure here.
*/
var MapSum = function () {
this.store = {};
this.prefixs = [];
};
/**
* @param {string} key
* @param {number} val
* @return {void}
*/
MapSum.prototype.insert = function (key, val) {
if (!this.store[key]) {
this.prefixs.push(key);
}
this.store[key] = val;
};
/**
* @param {string} prefix
* @return {number}
*/
MapSum.prototype.sum = function (prefix) {
var len = this.prefixs.length;
var sum = 0;
for (var i = 0; i < len; i++) {
var temp = this.prefixs[i];
if (temp.indexOf(prefix) === 0) {
sum += this.store[temp];
}
}
return sum;
};
/**
* Your MapSum object will be instantiated and called as such:
* var obj = Object.create(MapSum).createNew()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/
var a = new MapSum();
a.insert("apple", 3);
console.log(a.sum("ap"));
a.insert("app", 2)
console.log(a.sum("ap"));