Skip to content

Commit 08d1cc7

Browse files
authored
Two Sum (#5)
1 parent 07c56e3 commit 08d1cc7

File tree

4 files changed

+43
-0
lines changed

4 files changed

+43
-0
lines changed

src/leetcode/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Leetcode

src/leetcode/arrays/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Arrays
22

33
* [Merge Two Sorted Lists](#merge-two-sorted-lists)
4+
* [Two Sum](#two-sum)
45

56
## Merge Two Sorted Lists
67

@@ -39,3 +40,26 @@ export function mergeTwoLists(l1, l2) {
3940
return head.next;
4041
}
4142
```
43+
44+
## Two Sum
45+
46+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
47+
48+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
49+
50+
Example:
51+
52+
`[2, 7, 11, 15], 9 -> [0, 1]`
53+
54+
```javascript
55+
export function(nums, target) {
56+
const map = {};
57+
for (let i = 0; i < nums.length; i += 1) {
58+
const comp = target - nums[i];
59+
if (comp in map) {
60+
return [map[comp], i]
61+
}
62+
map[nums[i]] = i;
63+
}
64+
};
65+
```

src/leetcode/arrays/two_sum.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
export default function (nums, target) {
3+
const map = {};
4+
5+
for (let i = 0; i < nums.length; i += 1) {
6+
const comp = target - nums[i];
7+
if (comp in map) {
8+
return [map[comp], i];
9+
}
10+
map[nums[i]] = i;
11+
}
12+
return null;
13+
}

tests/leetcode/two_sum.test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import twoSum from '../../src/leetcode/arrays/two_sum';
2+
3+
test('should find sum', () => {
4+
expect(twoSum([2, 7, 11, 15], 9)).toEqual([0, 1]);
5+
});

0 commit comments

Comments
 (0)