forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYjason-K.ts
More file actions
25 lines (25 loc) ยท 1015 Bytes
/
Yjason-K.ts
File metadata and controls
25 lines (25 loc) ยท 1015 Bytes
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
/**
* ์ฃผ์ด์ง ๋ฐฐ์ด์์ ๋ ์ซ์์ ํฉ์ด target์ด ๋๋ idx ์์ ๋ฐํํ๋ ํจ์
* - ์๊ฐ ๋ณต์ก๋: O(n)
* - ํ๋ฒ์ ๋ฐฐ์ด์ ์ํํ๋ฉฐ Map์ ๊ฐ์ ์ ์ฅํ๊ณ , Map์์ ๊ฐ์ ์ฐพ์
* - ๊ณต๊ฐ ๋ณต์ก๋: O(n)
* - ์ซ์์ ๊ทธ๋์ idx๋ฅผ ์์ผ๋กํ๋ Map
*
* @param {number[]} nums - ์ซ์ ๋ฐฐ์ด
* @param {number} target - ํ๊ฒ ํฉ
* @returns {number[]} - ํฉ์ ๋ง๋ค ์ ์๋ idx ๋ฐฐ์ด
*/
function twoSum(nums: number[], target: number): number[] {
const map = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const cur = nums[i]; // ํ์ฌ ๊ฐ
const reamin = target - cur; // ๋๋จธ์ง
if (map.has(reamin)) {
// Non-null assertion operator(!)๋ฅผ ์ฌ์ฉํ์ฌ undefined๊ฐ ์๋์ ๋จ์ธ
return [map.get(reamin)!, i];
}
// ๋๋จธ์ง๋ฅผ ์ฐพ์ง ๋ชปํ ๊ฒฝ์ฐ ํ์ฌ ๊ฐ์ ์ ์ฅ
map.set(cur, i);
}
return []; // ๋ชฉํ ํฉ์ ๋ง๋ค ์ ์๋ ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ ๋น ๋ฐฐ์ด ๋ฐํ
}