Skip to content

Commit 1abcdb6

Browse files
committed
missing-number solution (ts)
1 parent 4824991 commit 1abcdb6

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* https://leetcode.com/problems/missing-number/
3+
*
4+
* ๋ฌธ์ œ ์„ค๋ช…:
5+
* - 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ˆซ์ž ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋น ์ง„ ๊ธธ์ด n์˜ ๋ฐฐ์—ด nums๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.
6+
* - ์ด ๋•Œ, ๋ˆ„๋ฝ๋œ ์ˆซ์ž ํ•˜๋‚˜๋ฅผ ์ฐพ์•„ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.
7+
*
8+
* ์กฐ๊ฑด:
9+
* - nums.length == n
10+
* - nums์˜ ์š”์†Œ๋Š” ๊ณ ์œ ํ•˜๋ฉฐ [0, n] ๋ฒ”์œ„์˜ ์ •์ˆ˜๋ฅผ ํฌํ•จํ•ฉ๋‹ˆ๋‹ค.
11+
*
12+
* ํ’€์ด ์•„์ด๋””์–ด:
13+
* - 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ดํ•ฉ์„ ๊ณต์‹์œผ๋กœ ๊ณ„์‚ฐํ•œ ํ›„, ์‹ค์ œ ๋ฐฐ์—ด์˜ ์ดํ•ฉ์„ ๋บ๋‹ˆ๋‹ค.
14+
* 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ํ•ฉ ๊ณต์‹:
15+
* 0 + 1 + 2 + ... + n = n(n + 1)/2
16+
* - ๋น ์ง„ ์ˆซ์ž = ๊ธฐ๋Œ€ ์ดํ•ฉ - ์‹ค์ œ ์ดํ•ฉ
17+
*
18+
* TC: O(n)
19+
* - ๋ฐฐ์—ด ์ˆœํšŒ๋กœ ์‹ค์ œ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฐ O(n)
20+
*
21+
* SC: O(1)
22+
* - ์ถ”๊ฐ€ ๊ณต๊ฐ„ ์—†์ด ์ƒ์ˆ˜ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ
23+
*/
24+
25+
function missingNumber(nums: number[]): number {
26+
const expectedSum = Math.floor((nums.length * (nums.length + 1)) / 2);
27+
const actualSum = nums.reduce((acc, cur) => acc + cur);
28+
return expectedSum - actualSum;
29+
}

0 commit comments

Comments
ย (0)