Skip to content

Commit 46057fc

Browse files
committed
solution: two sum
1 parent 6fdb0fa commit 46057fc

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* @description
3+
* time complexity: O(n^2)
4+
* space complexity: O(1)
5+
* ํ’€์ด ๋ฐฉ๋ฒ•:
6+
* ์นด์šดํ„ฐ๋ฅผ ํ†ตํ•ด ๋ฐ˜๋ณต๋ฌธ ๋Œ๊ธฐ
7+
* ๊ฒ‰์œผ๋กœ๋Š” ๋ฐ˜๋ณต๋ฌธ์ด ํ•œ๊ฐœ ๊ฐ™์•„๋ณด์ด์ง€๋งŒ ์ด์ค‘๋ฐ˜๋ณต๋ฌธ์ด๋‹ค.
8+
* @param {number[]} nums
9+
* @param {number} target
10+
* @return {number[]}
11+
*/
12+
const twoSumSoluton1 = function (nums, target) {
13+
let left = 0;
14+
let right = 1;
15+
while (left < nums.length - 1) {
16+
const sum = nums[left] + nums[right];
17+
if (sum === target) {
18+
return [left, right];
19+
}
20+
21+
if (right < nums.length - 1) {
22+
right += 1;
23+
} else {
24+
left += 1;
25+
right = left + 1;
26+
}
27+
}
28+
};
29+
30+
/**
31+
* @description
32+
* ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ํ’€์ด๋ฅผ ๋ณด๊ณ  ๊ฐœ์„ ํ•œ ์†”๋ฃจ์…˜
33+
* time complexity: O(n)
34+
* space complexity: O(n)
35+
* ํ’€์ด ๋ฐฉ๋ฒ•:
36+
* ์ด์ „ ๊ฐ’๋“ค ์ค‘์— ์›ํ•˜๋Š” ๊ฐ’์ด ์žˆ๋Š”์ง€๋งŒ ํ™•์ธ ํ›„ ์ถ”์ถœ, ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ํฌ๊ฒŒ ๊ฐ์†Œ์‹œํ‚ด
37+
* ํ•˜์ง€๋งŒ ํ•ด์‰ฌ๋งต์„ ๋งŒ๋“ค์–ด์•ผํ•ด์„œ ๊ณต๊ฐ„๋ณต์žก๋„๋Š” O(n)์œผ๋กœ ๋ณ€๊ฒฝ
38+
* @param {number[]} nums
39+
* @param {number} target
40+
* @return {number[]}
41+
*/
42+
const twoSumSoluton2 = function (nums, target) {
43+
const hashMap = new Map();
44+
45+
for (let i = 0; i < nums.length; i += 1) {
46+
const calculatedTarget = target - nums[i];
47+
if (hashMap.has(calculatedTarget)) {
48+
return [i, hashMap.get(calculatedTarget)];
49+
}
50+
51+
hashMap.set(nums[i], i);
52+
}
53+
54+
return [];
55+
};

0 commit comments

Comments
ย (0)