-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.two-sum.js
More file actions
56 lines (48 loc) · 1.57 KB
/
1.two-sum.js
File metadata and controls
56 lines (48 loc) · 1.57 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
/*
* @lc app=leetcode id=1 lang=javascript
*
* [1] Two Sum
*/
// @lc code=start
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
// Brute force method
// Given an array nums, go through each of the elements and add the prev to the next.
// Save each result in an array.
// Put the indices of the two elements that gave each result inside another array.
// Iterate over the addition array and check if any of the results is equal to the target.
// Get the index of the result in the addition array and use it to get the indices stored in the second array.
var twoSum = function (nums, target) {
let additionArr = [];
let indexArr = [];
nums.flatMap((num, index, arr) => {
const additionResult = arr[index] + arr[index + 1];
if (isNaN(additionResult)) {
return [];
} else {
additionArr.push(additionResult);
indexArr.push([index, index + 1]);
}
});
/* for (result of additionArr) {
if (result === target) {
const indexOfResult = additionArr.indexOf(result);
const indicesGivingResult = indexArr[indexOfResult];
return indicesGivingResult;
}
} */
// Using this also gives the same output as the for-of loop
const result = additionArr.flatMap((val, index, arr) => {
if (val === target) {
const indexOfVal = arr.indexOf(val);
return indexArr[indexOfVal];
}
});
return result.filter(arr => arr !== undefined);
// Not including the variable result and returning this outputs an undefined
// because the twoSum function has nothing to return.
};
// @lc code=end