-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.js
More file actions
55 lines (41 loc) · 1.06 KB
/
twoSum.js
File metadata and controls
55 lines (41 loc) · 1.06 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
// Find two numbers in a sorted array that sum to a target
let sortedArray = [-3, -1, 1, 3, 5, 6]
let sum = 6
function sumByBruteForce(array, sum) {
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] + array[j] === sum) {
return [array[i] , array[j]];
}
}
}
return false;
}
/** Two Pointer **/
function sumByTwoPointers(array, sum) {
left = 0
right = array.length - 1
while (left < right) {
current = array[left] + array[right]
if (sum = current) {
return (left + 1, right + 1)
} else if (sum < current) {
right--
} else {
left++
}
}
}
/** Hashmap/Map **/
var twoSum = function(nums, target) {
const sum = new Map()
for (let i = 0; i < nums.length; i++){
let diff = target - nums[i]
if(!sum.has(diff) ){
sum.set(nums[i], i)
} else {
let index = sum.get(diff)
return [index, i]
}
}
};