-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo-sum.js
More file actions
38 lines (31 loc) · 752 Bytes
/
Copy pathtwo-sum.js
File metadata and controls
38 lines (31 loc) · 752 Bytes
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
// Complexity O(n2)
var twoSumBruteForce = function (nums, target) {
let result = [];
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result = [i, j];
break;
}
}
}
return result;
};
// Complexity O(n)
var twoSum = function (nums, target) {
let map = {};
for (let i = 0; i < nums.length; i++) {
map[nums[i]] = i;
}
for (let i = 0; i < nums.length - 1; i++) {
const remaining = target - nums[i];
if (remaining in map && map[remaining] != i) {
return [i, map[remaining]];
}
}
return [];
};
var arr = [2, 7, 11, 15];
var t = 9;
console.log(twoSumBruteForce(arr, t));
console.log(twoSum(arr, t));