forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhewchews.ts
More file actions
39 lines (35 loc) ยท 1.15 KB
/
whewchews.ts
File metadata and controls
39 lines (35 loc) ยท 1.15 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
37
38
39
/*
* ์กฐ๊ฑด
* [0, n] ์ค์ ์๋ ๊ฐ์ ๋ฆฌํด, n == nums.length
* ๋ชจ๋ ๊ฐ์ unique
* ์์ด๋์ด
* => nums.length๋ ์ค์ ๋ฐฐ์ด index๋ณด๋ค 1์ด ๋ ํฌ๊ธฐ ๋๋ฌธ์ ํญ์ ์๋ ๊ฐ์ด 1๊ฐ ์กด์ฌํจ
* 0๋ถํฐ n๊น์ง์ ๋ชจ๋ ๊ฐ์ set์ ์ ์ฅํด๋๋ค.
* set ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๋
* 1. nums์ ๋ค์ด์ค๋ ๊ฐ์ด ์ค๋ณต๊ฐ์ด ์กด์ฌํ์ง ์๊ธฐ ๋๋ฌธ
* 2. ๊ฐ์ ๋์์ ๋ฐฐ์ด์์ ํ๊ฒ ๋๋ฉด
* ๊ฐ ์ธ๋ฑ์ค๋ฅผ 1๋ก ๋๊ณ ๊ฐ์ด ์์๋๋ง๋ค 0์ผ๋ก ๋ณ๊ฒฝ, 1์ด ์๋ index๋ฅผ ์ฐพ์์ผ๋ก ํ ์ ์์
* => ์ด ๊ฒฝ์ฐ, ๋จ์ ๊ฐ์ ์ฐพ์ ๋ ๋ฐฐ์ด์ ํ๋ฒ ๋ค ๋์์ผ ํด์ ์๊ฐ๋ณต์ก๋๊ฐ O(n) ๋ ์์๋จ.
* nums ๋ฐฐ์ด์ ๋๋ฉฐ ๊ฐ์ด ์์๋ ๋ง๋ค set์์ ๊ฐ์ ์ญ์ ํ๋ค.
* set์์ ๋จ์ ๊ฐ์ ์ฐพ์ ๋ฆฌํดํด์ค๋ค.
*
*/
function missingNumber(nums: number[]): number {
// TC: O(n)
// SC: O(n)
const numSet: Set<number> = new Set(
Array(nums.length + 1)
.fill(0)
.map((v, i) => i)
);
// TC: O(n)
nums.forEach((n) => {
numSet.delete(n);
});
// TC: O(1)
// SC: O(1)
const [lastNum] = numSet.values();
return lastNum;
}
// TC: O(n)
// SC: O(n)