forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhi-rachel.ts
More file actions
29 lines (28 loc) ยท 975 Bytes
/
hi-rachel.ts
File metadata and controls
29 lines (28 loc) ยท 975 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
26
27
28
29
/**
* https://leetcode.com/problems/missing-number/
*
* ๋ฌธ์ ์ค๋ช
:
* - 0๋ถํฐ n๊น์ง์ ์ซ์ ์ค ํ๋๊ฐ ๋น ์ง ๊ธธ์ด n์ ๋ฐฐ์ด nums๊ฐ ์ฃผ์ด์ง๋๋ค.
* - ์ด ๋, ๋๋ฝ๋ ์ซ์ ํ๋๋ฅผ ์ฐพ์ ๋ฐํํ์ธ์.
*
* ์กฐ๊ฑด:
* - nums.length == n
* - nums์ ์์๋ ๊ณ ์ ํ๋ฉฐ [0, n] ๋ฒ์์ ์ ์๋ฅผ ํฌํจํฉ๋๋ค.
*
* ํ์ด ์์ด๋์ด:
* - 0๋ถํฐ n๊น์ง์ ์ดํฉ์ ๊ณต์์ผ๋ก ๊ณ์ฐํ ํ, ์ค์ ๋ฐฐ์ด์ ์ดํฉ์ ๋บ๋๋ค.
* 0๋ถํฐ n๊น์ง์ ํฉ ๊ณต์:
* 0 + 1 + 2 + ... + n = n(n + 1)/2
* - ๋น ์ง ์ซ์ = ๊ธฐ๋ ์ดํฉ - ์ค์ ์ดํฉ
*
* TC: O(n)
* - ๋ฐฐ์ด ์ํ๋ก ์ค์ ํฉ์ ๊ตฌํ๋ ๋ฐ O(n)
*
* SC: O(1)
* - ์ถ๊ฐ ๊ณต๊ฐ ์์ด ์์ ๋ณ์๋ง ์ฌ์ฉ
*/
function missingNumber(nums: number[]): number {
const expectedSum = Math.floor((nums.length * (nums.length + 1)) / 2);
const actualSum = nums.reduce((acc, cur) => acc + cur);
return expectedSum - actualSum;
}