forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclara-shin.js
More file actions
36 lines (30 loc) ยท 1.26 KB
/
clara-shin.js
File metadata and controls
36 lines (30 loc) ยท 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* ๋ฌธ์ ํ์
:
* ์ ์ ๋ฐฐ์ด nums์ ๋ชฉํ๊ฐ target์ด ์ฃผ์ด์ก์ ๋, ๋ ์ซ์๋ฅผ ๋ํด์ target์ด ๋๋ ๋ ์์ ์ธ๋ฑ์ค๋ฅผ ์ฐพ๋ ๋ฌธ์
* follow-up: ๋ธ๋ฃจํธ ํฌ์ค(์ด์ค ๋ฐ๋ณต๋ฌธ -> O(n^2)) ์ ๊ทผ๋ฒ๋ณด๋ค ํจ์จ์ ์ธ ํด์๋งต์ ์ฌ์ฉํ์ฌ ํด๊ฒฐ
* => ๋ฐฐ์ด์ ํ ๋ฒ๋ง ์ํํ๊ธฐ ๋๋ฌธ์ ์ ํ ์๊ฐ ๋ณต์ก๋ O(n)
*
* ์ ๊ทผ ๋ฐฉ์:
* (1) ์ซ์์ ํด๋น ์ธ๋ฑ์ค๋ฅผ ์ ์ฅํ๊ธฐ ์ํด Map ๊ฐ์ฒด ์ฌ์ฉ
* (2) ๋ฐฐ์ด์ ํ ๋ฒ๋ง ์ํํ๋ฉด์ ๊ฐ ์์๋ฅผ ํ์ธํ๋๋ฐ,
* (3) ๊ฐ ์ซ์์ ๋ํด, target - ํ์ฌ ์ซ์๊ฐ ์ด๋ฏธ ํด์๋งต์ ์๋์ง ํ์ธํด์
* ์๋ค๋ฉด: ์ฐพ์ ์ซ์์ ํ์ฌ ์ซ์์ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๊ณ
* ์๋ค๋ฉด: ํ์ฌ ์ซ์์ ๊ทธ ์ธ๋ฑ์ค๋ฅผ ํด์๋งต์ ์ ์ฅํ๊ณ ๊ณ์ ์งํ
*/
/**
* @param {number[]} nums - ์ ์ ๋ฐฐ์ด
* @param {number} target - ๋ชฉํ ํฉ๊ณ ๊ฐ
* @return {number[]} - ํฉ์ด ๋ชฉํ๊ฐ์ด ๋๋ ๋ ์์ ์ธ๋ฑ์ค
*/
var twoSum = function (nums, target) {
const numMap = new Map();
for (let i = 0; i < nums.length; i++) {
const currentNum = nums[i];
const complement = target - currentNum;
if (numMap.has(complement)) {
return [numMap.get(complement), i];
}
numMap.set(currentNum, i);
}
return [];
};