-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1-Two Number Sum.js
63 lines (53 loc) · 1.32 KB
/
1-Two Number Sum.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
52
53
54
55
56
57
58
59
60
61
62
63
// SOLUTION 1
function twoNumberSum(array, targetSum) {
// Write your code here.
const arr = array;
const tempTarget = targetSum;
let i = 0;
let result = [];
while (i < arr.length) {
let picked = arr[i];
for (let index = i + 1; index < arr.length; index++) {
if (picked + arr[index] === tempTarget) {
result.push(arr[index]);
result.push(picked);
break;
}
}
i += 1;
}
return result;
}
// Do not edit the line below.
exports.twoNumberSum = twoNumberSum;
// SOLUTION 2
function twoNumberSum(array, targetSum) {
// Write your code here.
const set = new Set();
for (let item of array) {
const complement = targetSum - item;
if (set.has(complement)) {
return [item, complement];
}
set.add(item);
}
return [];
}
// Do not edit the line below.
exports.twoNumberSum = twoNumberSum;
// SOLUTION 3
function twoNumberSum(array, targetSum) {
// Write your code here.
const temp = { [array[0]]: true };
for (let i = 1; i < array.length; i++) {
console.log(temp);
if (temp[targetSum - array[i]]) {
return [targetSum - array[i], array[i]];
} else {
temp[array[i]] = true;
}
}
return [];
}
// Do not edit the line below.
exports.twoNumberSum = twoNumberSum;