forked from codesONLY/JavaScriptONLY
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.js
More file actions
22 lines (22 loc) · 670 Bytes
/
Copy pathtwoSum.js
File metadata and controls
22 lines (22 loc) · 670 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
/* A brute-force approach. Traverse the nums array via two pointers i and j and return
indexes stored in an array if the total matches the target*/
var twoSum = function (nums, target) {
let targetResult = [];
// traverse the array via two pointers
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
// check if the sum of two numbers is equal to the target
if (nums[i] + nums[j] === target) {
targetResult.push(i);
targetResult.push(j);
}
}
}
// return the array with indexes
return targetResult;
};