Skip to content

Commit 9f88e7c

Browse files
committed
add: twoSum solution.
1 parent 2ee4f1f commit 9f88e7c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

algorithms/js/twoSum/twoSum.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Source : https://oj.leetcode.com/problems/two-sum/
2+
// Author : Albin Zeng.
3+
// Date : 2017-02-26
4+
5+
/**********************************************************************************
6+
*
7+
* Given an array of integers, find two numbers such that they add up to a specific target number.
8+
*
9+
* The function twoSum should return indices of the two numbers such that they add up to the target,
10+
* where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
11+
* are not zero-based.
12+
*
13+
* You may assume that each input would have exactly one solution.
14+
*
15+
* Input: numbers={2, 7, 11, 15}, target=9
16+
* Output: index1=1, index2=2
17+
*
18+
*
19+
**********************************************************************************/
20+
21+
/**
22+
* @param {number[]} nums
23+
* @param {number} target
24+
* @return {number[]}
25+
*/
26+
var twoSum = function(nums, target) {
27+
const map = {};
28+
let i = 0;
29+
for (; i < nums.length; i++) {
30+
if (undefined === map[target - nums[i]]) {
31+
map[nums[i]] = i;
32+
} else {
33+
return [map[target - nums[i]], i];
34+
}
35+
}
36+
};

0 commit comments

Comments
 (0)