-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0001_twoSum.js
More file actions
50 lines (47 loc) · 1.04 KB
/
0001_twoSum.js
File metadata and controls
50 lines (47 loc) · 1.04 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
/**
* Given nums = [2, 7, 11, 15], target = 9,
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0, 1].
*/
/**
* Time Conplexity: O(N²)
* Space Conplexity: O(1)
*/
const twoSumBruteForce = (nums, target) => {
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};
/**
* Time Conplexity: O(N)
* Space Conplexity: O(N)
*/
const twoSumTwoPassHashTable = (nums, target) => {
const comp = {};
for (let i = 0; i < nums.length; i++) {
comp[nums[i]] = i;
}
for (let i = 0; i < nums.length; i++) {
const rest = target - nums[i];
if (comp[rest] && comp[rest] != i) {
return [i, comp[rest]];
}
}
};
/**
* Time Conplexity: O(N)
* Space Conplexity: O(N)
*/
const twoSumOnePassHashTable = function (nums, target) {
const comp = {};
for (let i = 0; i < nums.length; i++) {
if (comp[target - nums[i]] !== undefined) {
return [comp[target - nums[i]], i];
}
comp[nums[i]] = i;
}
};