Skip to content

Commit 0148348

Browse files
committed
Add solution #1
1 parent e46c027 commit 0148348

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
|#|Title|Difficulty|
88
|:---|:---|:---|
9+
1|[Two Sum](./0001-two-sum.js)|Easy|
910
4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard|
1011
31|[Next Permutation](./0031-next-permutation.js)|Medium|
1112
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|

solutions/0001-two-sum.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 1. Two Sum
3+
* https://leetcode.com/problems/two-sum/
4+
* Difficulty: Easy
5+
*
6+
* Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`.
7+
*
8+
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
9+
*
10+
* You can return the answer in any order.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @param {number} target
16+
* @return {number[]}
17+
*/
18+
var twoSum = function(nums, target) {
19+
const map = new Map();
20+
21+
for (let i = 0; i < nums.length; i++) {
22+
const diff = target - nums[i];
23+
24+
if (map.has(diff)) {
25+
return [map.get(diff), i];
26+
}
27+
28+
map.set(nums[i], i);
29+
}
30+
};

0 commit comments

Comments
 (0)