Skip to content

Commit 1d4afa4

Browse files
authored
Create 170-two-sum-iii-data-structure-design.js
1 parent ad857f0 commit 1d4afa4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Initialize your data structure here.
3+
*/
4+
const TwoSum = function() {
5+
this.hm = new Map();
6+
};
7+
8+
/**
9+
* Add the number to an internal data structure..
10+
* @param {number} number
11+
* @return {void}
12+
*/
13+
TwoSum.prototype.add = function(number) {
14+
this.hm.set(number, (this.hm.get(number) || 0) + 1);
15+
};
16+
17+
/**
18+
* Find if there exists any pair of numbers which sum is equal to the value.
19+
* @param {number} value
20+
* @return {boolean}
21+
*/
22+
TwoSum.prototype.find = function(value) {
23+
for (let item of this.hm) {
24+
let target = value - item[0];
25+
if (this.hm.has(target)) {
26+
if (target !== item[0] || this.hm.get(target) > 1) return true;
27+
}
28+
}
29+
return false;
30+
};
31+
32+
/**
33+
* Your TwoSum object will be instantiated and called as such:
34+
* var obj = new TwoSum()
35+
* obj.add(number)
36+
* var param_2 = obj.find(value)
37+
*/

0 commit comments

Comments
 (0)