-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwoSum.js
75 lines (64 loc) · 1.91 KB
/
twoSum.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
// ===============================================================
// Given an array of integers "nums" and an integer "target", return
// indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution,
// and you may not use the same element twice.
// You can return the answer in any order.
// https://leetcode.com/problems/two-sum/
// ===============================================================
// Output: [0,1]
// Output: Because nums[0] + nums[1] == 9, we return [0, 1].
// const twoSum = (nums, target) => {
// let storage = {};
// for (let [index, num] of nums.entries()) {
// if (storage[num] !== undefined) return [storage[num], index];
// storage[target - num] = index;
// }
// };
//////////////////////////////////////////////////
//
/////////////////////////////////////////////////
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) return nums[(i, j)];
}
}
}
// Space - O(1)
// Time - O(N^2)
// What can we do to improve this algo?
// Input: nums = [2,7,11,15], target = 9
function twoSum(nums, target) {
let memory = {};
for (let i = 0; i < nums.length; i++) {
if (memory[nums[i]] === undefined) {
memory[target - nums[i]] = i;
} else {
return [i, memory[nums[i]]];
}
}
}
// The Brute Force
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j <= nums.length; j++) {
if (i === j) {
continue;
}
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
};
var twoSum = function (nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const compliment = target - nums[i];
if (map.has(compliment)) {
return [map.get(compliment), i];
}
map.set(nums[i], i);
}
};