Skip to content

Commit 82151f6

Browse files
Johanes Boas Badiaabranhe
authored andcommitted
add 2sum.js
1 parent 9c44334 commit 82151f6

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

math/2sum.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// File name: 2sum.js
2+
// Author: boasmarbun (https://github.com/boasmarbun)
3+
// Date created: 02/10/2020
4+
5+
function twoSum (nums, target) {
6+
var diff = 0;
7+
for (var firstIndex = 0; firstIndex <= nums.length; firstIndex++) {
8+
diff = target - nums[firstIndex];
9+
var secondIndex = nums.indexOf(diff, firstIndex+1);
10+
if(secondIndex != -1) {
11+
return [firstIndex, secondIndex];
12+
}
13+
}
14+
return [0];
15+
};
16+
17+
// uncomment below for testing
18+
// var testArray1 = [1,2,3,9]
19+
// var target1 = 5
20+
// var testArray2 = [0,3,4,0]
21+
// var target2 = 0
22+
// var testArray3 = [-2, -3, -7, -13, -6]
23+
// var target3 = -8
24+
// var testArray4 = []
25+
// var target4 = 2
26+
27+
// console.log(twoSum(testArray1, target1))
28+
// console.log(twoSum(testArray2, target2))
29+
// console.log(twoSum(testArray3, target3))
30+
// console.log(twoSum(testArray4, target4))

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy