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
29 lines (27 loc) ยท 1.24 KB
/
Yjason-K.ts
File metadata and controls
29 lines (27 loc) ยท 1.24 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
/**
* 0๋ถํฐ n๊น์ง์ ์ซ์ ์ค ๋ฐฐ์ด์์ ๋๋ฝ๋ ์ซ์๋ฅผ ์ฐพ๋ ํจ์
* @param {number[]} nums - 0๋ถํฐ n๊น์ง์ ์ซ์๊ฐ ํฌํจ๋ ๋ฐฐ์ด (์์๋ ๋ฌด์์์ด๋ฉฐ ์ผ๋ถ ์ซ์๊ฐ ๋๋ฝ๋ ์ ์์)
* @returns {number} - ๋ฐฐ์ด์์ ๋๋ฝ๋ ์ซ์
*
* ์๊ฐ ๋ณต์ก๋: O(n)
* - Set์ Hash Table๋ก ๊ตฌํ๋์ด has ๋ฉ์๋๊ฐ Array.includes ๋ฉ์๋๋ณด๋ค ์ ๋ฆฌ
* - Set์ ์์ฑํ๋ ๋ฐ O(n) ์๊ฐ์ด ์์
* - ๋ฐฐ์ด ๊ธธ์ด๋งํผ ๋ฐ๋ณต๋ฌธ์ ๋๋ฉด์ Set์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ํ์ธํ๋ ๋ฐ O(1) * n = O(n)
* - ๊ฒฐ๊ณผ์ ์ผ๋ก O(n) + O(n) = O(n)
*
* ๊ณต๊ฐ ๋ณต์ก๋: O(n)
* - Set ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ์ฌ ์
๋ ฅ ๋ฐฐ์ด์ ๋ชจ๋ ์์๋ฅผ ์ ์ฅํ๋ฏ๋ก O(n)์ ์ถ๊ฐ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ
*/
function missingNumber(nums: number[]): number {
// ๋ฐฐ์ด์ ์ซ์๋ฅผ ๋ชจ๋ Set์ ์ถ๊ฐํ์ฌ ์ค๋ณต ์ ๊ฑฐ
const distinctSet = new Set([...nums]);
// 0๋ถํฐ n๊น์ง์ ์ซ์ ์ค์์ ๋๋ฝ๋ ์ซ์๋ฅผ ํ์
for (let i = 0; i < nums.length; i++) {
// Set์ i๊ฐ ์กด์ฌํ์ง ์์ผ๋ฉด i๊ฐ ๋๋ฝ๋ ์ซ์
if (!distinctSet.has(i)) {
return i;
}
}
// ๋ชจ๋ ์ซ์๊ฐ Set์ ์กด์ฌํ๋ฉด n์ด ๋๋ฝ๋ ์ซ์
return nums.length;
}