|
1 | | -/** |
2 | | - * Initialize your data structure here. |
3 | | - */ |
4 | 1 | var TwoSum = function () {
|
5 | | - this.numbers = []; |
6 | | - this.sums = new Map(); |
| 2 | + this.map = new Map(); |
7 | 3 | };
|
8 | 4 |
|
9 | 5 | /**
|
10 | | - * Add the number to an internal data structure.. |
11 | 6 | * @param {number} number
|
12 | 7 | * @return {void}
|
13 | 8 | */
|
14 | 9 | TwoSum.prototype.add = function (number) {
|
15 | | - for(leti=0;i<this.numbers.length;i++) { |
16 | | - consts=this.numbers[i] + number; |
17 | | - |
18 | | - this.sums.set(s,true); |
| 10 | + if(this.map.has(number)) { |
| 11 | + this.map.set(number,this.map.get(number) + 1); |
| 12 | +}else{ |
| 13 | + this.map.set(number,1); |
19 | 14 | }
|
20 | | - |
21 | | - this.numbers.push(number); |
22 | 15 | };
|
23 | 16 |
|
24 | 17 | /**
|
25 | | - * Find if there exists any pair of numbers which sum is equal to the value. |
26 | 18 | * @param {number} value
|
27 | 19 | * @return {boolean}
|
28 | 20 | */
|
29 | 21 | TwoSum.prototype.find = function (value) {
|
30 | | - return this.sums.has(value) ? this.sums.get(value) : false; |
| 22 | + const keys = this.map.keys(); |
| 23 | + for (key of keys) { |
| 24 | + const current = this.map.get(key); |
| 25 | + const complement = value - key; |
| 26 | + |
| 27 | + if (complement === key) { |
| 28 | + if (current > 1) { |
| 29 | + return true; |
| 30 | + } |
| 31 | + } else { |
| 32 | + if (this.map.has(complement)) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return false; |
31 | 39 | };
|
32 | 40 |
|
33 | 41 | /**
|
34 | 42 | * Your TwoSum object will be instantiated and called as such:
|
35 | | - * var obj = Object.create(TwoSum).createNew() |
| 43 | + * var obj = new TwoSum() |
36 | 44 | * obj.add(number)
|
37 | 45 | * var param_2 = obj.find(value)
|
38 | 46 | */
|
0 commit comments