Skip to content

Commit 324f5c0

Browse files
committed
Two Sum Solutions
1 parent f449a1e commit 324f5c0

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
7+
/**
8+
* Runtime: 107ms, Memory: 49.52MB
9+
* Time complexity: O(n^2)
10+
* Space complexity: O(n^2)
11+
*
12+
* **/
13+
14+
var twoSum = function (nums, target) {
15+
const answer = [];
16+
for (let i = 0; i < nums.length - 1; i++) {
17+
for (let j = i + 1; j < nums.length; j++) {
18+
if (nums[i] + nums[j] === target) {
19+
return [i, j];
20+
}
21+
}
22+
}
23+
};
24+
25+
/**
26+
* @param {number[]} nums
27+
* @param {number} target
28+
* @return {number[]}
29+
*/
30+
31+
/**
32+
* ๋‹ค๋ฅธ ํ’€์ด: two์˜ sum ์ด๋‹ˆ๊นŒ target - ํ˜„์žฌ ๊ฐ’์„ ํ•œ ๋’ค, ๋‚˜๋จธ์ง€ ๊ฐ’์ด ๋ฐฐ์—ด์— ์žˆ๋Š”์ง€ ์ฐพ๋Š” ๋ฐฉ๋ฒ•.
33+
* ์ด ๊ณผ์ •์—์„œ ํ•ด์‹œ๋งต์„ ์‚ฌ์šฉํ•ด์„œ target - ํ˜„์žฌ ๊ฐ’์ด map ์— ์กด์žฌํ•˜๋ฉด return
34+
* ์—†๋‹ค๋ฉด map์— ๋‚˜๋จธ์ง€ ๊ฐ’๊ณผ ๊ทธ์— ํ•ด๋‹นํ•˜๋Š” ์ธ๋ฑ์Šค๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.
35+
* ๊ทธ๋Ÿผ ์ถ”ํ›„์—๋Š” ๋‚˜๋จธ์ง€ ๊ฐ’์„ map์—์„œ O(1)๋กœ ์ฐพ๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค.
36+
*
37+
* Runtime: 49ms, Memory: 49.52MB
38+
* Time complexity: O(n)
39+
* Space complexity: O(n)
40+
* **/
41+
42+
var twoSum = function (nums, target) {
43+
let map = new Map();
44+
45+
for (i = 0; i < nums.length; i++) {
46+
if (map.has(target - nums[i])) return [map.get(target - nums[i]), i];
47+
map.set(nums[i], i);
48+
}
49+
};

0 commit comments

Comments
ย (0)