-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0001-two-sum.js
79 lines (65 loc) · 2.07 KB
/
0001-two-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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Brute Force - Linear Search
* Time O(N^2) | Space O(1)
* https://leetcode.com/problems/two-sum/
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = (nums, target) => {
for (let curr = 0; curr < nums.length; curr++) {/* Time O(N) */
const complement = target - nums[curr];
for (let next = (curr + 1); next < nums.length; next++) {/* Time O(N) */
const num = nums[next];
const isTarget = num === complement
if (isTarget) return [ curr, next ];
}
}
return [ -1, -1 ];
}
/**
* Hash Map - 2 Pass
* Time O(N) | Space O(N)
* https://leetcode.com/problems/two-sum/
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = (nums, target) => {
const map = getMap(nums); /* Time O(N) | Space O(N) */
return getSum(nums, target, map)/* Time O(N) */
}
const getMap = (nums, map = new Map()) => {
for (let index = 0; index < nums.length; index++) {/* Time O(N) */
map.set(nums[index], index); /* Space O(N) */
}
return map
}
const getSum = (nums, target, map) => {
for (let index = 0; index < nums.length; index++) {/* Time O(N) */
const complement = target - nums[index];
const sumIndex = map.get(complement);
const isTarget = map.has(complement) && (map.get(complement) !== index)
if (isTarget) return [ index, sumIndex ]
}
return [ -1, -1 ];
}
/**
* Hash Map - 1 Pass
* Time O(N) | Space O(N)
* https://leetcode.com/problems/two-sum/
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = (nums, target, map = new Map()) => {
for (let index = 0; index < nums.length; index++) {/* Time O(N) */
const num = nums[index];
const complement = (target - num);
const sumIndex = map.get(complement);
const isTarget = map.has(complement)
if (isTarget) return [ index, sumIndex ];
map.set(num, index); /* Space O(N) */
}
return [ -1, -1 ];
}