-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path170-two-sum-iii-data-structure-design.js
More file actions
56 lines (51 loc) · 1.05 KB
/
170-two-sum-iii-data-structure-design.js
File metadata and controls
56 lines (51 loc) · 1.05 KB
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
52
53
54
55
56
var TwoSum = function () {
this.nums = [];
this.sorted = false;
};
/**
* @param {number} number
* @return {void}
*/
TwoSum.prototype.add = function (number) {
this.nums.push(number);
return this.nums;
this.sorted = false;
};
/**
* @param {number} value
* @return {boolean}
*/
TwoSum.prototype.find = function (value) {
// necesitamos ordenar nums.
if (!this.sorted) {
this.nums.sort((a, b) => a - b);
this.sorted = true;
}
let left = 0;
let right = this.nums.length - 1;
while (left < right) {
const sum = this.nums[left] + this.nums[right];
if (sum === value) {
console.log(value, 'found ->', left, right);
return true;
}
if (sum < value) {
left++;
} else {
right--;
}
}
return false;
};
/**
* Your TwoSum object will be instantiated and called as such:
* var obj = new TwoSum()
* obj.add(number)
* var param_2 = obj.find(value)
*/
const ts = new TwoSum();
console.log(ts.add(3));
console.log(ts.add(1));
console.log(ts.add(2));
console.log(ts.find(4));
console.log(ts.find(7));