Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ec94e20

Browse files
Improve solution for 170.
1 parent afe4e8d commit ec94e20

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed
Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,46 @@
1-
/**
2-
* Initialize your data structure here.
3-
*/
41
var TwoSum = function () {
5-
this.numbers = [];
6-
this.sums = new Map();
2+
this.map = new Map();
73
};
84

95
/**
10-
* Add the number to an internal data structure..
116
* @param {number} number
127
* @return {void}
138
*/
149
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);
1914
}
20-
21-
this.numbers.push(number);
2215
};
2316

2417
/**
25-
* Find if there exists any pair of numbers which sum is equal to the value.
2618
* @param {number} value
2719
* @return {boolean}
2820
*/
2921
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;
3139
};
3240

3341
/**
3442
* Your TwoSum object will be instantiated and called as such:
35-
* var obj = Object.create(TwoSum).createNew()
43+
* var obj = new TwoSum()
3644
* obj.add(number)
3745
* var param_2 = obj.find(value)
3846
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /