Skip to content

Commit 53c4022

Browse files
committed
two sum solution
1 parent b2a614b commit 53c4022

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

โ€Žtwo-sum/leehyeyun.jsโ€Ž

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
7+
/*
8+
์ •์ˆ˜ ๋ฐฐ์—ด nums์™€ ๋ชฉํ‘œ๊ฐ’ target์ด ์ฃผ์–ด์กŒ์„ ๋•Œ,
9+
๋‘ ์ˆ˜๋ฅผ ๋”ํ•ด target์ด ๋˜๋Š” ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜
10+
11+
์š”์ฒญํ˜•์‹ : twoSum(nums, target)
12+
์ž…๋ ฅํ˜•์‹ : nums๋Š” ์ •์ˆ˜ ๋ฐฐ์—ด, target์€ ์ •์ˆ˜
13+
์ถœ๋ ฅํ˜•์‹ : target์„ ๋งŒ์กฑํ•˜๋Š” ๋‘ ์ˆ˜์˜ ์ธ๋ฑ์Šค๋ฅผ [i, j] ํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜
14+
15+
์š”์ฒญ์˜ˆ์‹œ : twoSum([2,7,11,15], 9)
16+
์ถœ๋ ฅ์˜ˆ์‹œ : [0, 1]
17+
*/
18+
var twoSum = function(nums, target) {
19+
20+
const map = new Map();
21+
22+
for (let i=0; i<nums.length; i++) {
23+
24+
const diff = target - nums[i];
25+
26+
if (map.has(diff)) {
27+
return [map.get(diff), i];
28+
}
29+
30+
map.set(nums[i],i);
31+
32+
}
33+
};
34+
35+
console.log(twoSum([2,7,11,15], 9));
36+
console.log(twoSum([3,2,4], 6));
37+
console.log(twoSum([3,3], 6));

0 commit comments

Comments
ย (0)