Skip to content

Commit 06c3e1b

Browse files
committed
twosum
1 parent 18eec24 commit 06c3e1b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Programs/Exercise/twosum.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
/*
3+
Given an array of integers nums and an integer target, return indices
4+
of the two numbers such that they add up to target.
5+
6+
You may assume that each input would have exactly one solution,
7+
and you may not use the same element twice.
8+
9+
You can return the answer in any order.
10+
11+
Example 1:
12+
13+
Input: nums = [2,7,11,15], target = 9
14+
Output: [0,1]
15+
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
16+
Example 2:
17+
18+
Input: nums = [3,2,4], target = 6
19+
Output: [1,2]
20+
Example 3:
21+
22+
Input: nums = [3,3], target = 6
23+
Output: [0,1]
24+
*/
25+
26+
var twosum = function (nums, target) {
27+
for (let i = 0; i < nums.length; i++) {
28+
29+
for (let j = i + 1; j < nums.length; j++) {
30+
31+
if (nums[i] + nums[j] === target) {
32+
33+
return [i, j]
34+
}
35+
}
36+
}
37+
38+
return []
39+
};
40+
41+
console.log(twosum([2, 7, 11, 15], 9)); // [0,1]

0 commit comments

Comments
 (0)