forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmosco.js
More file actions
27 lines (24 loc) ยท 822 Bytes
/
smosco.js
File metadata and controls
27 lines (24 loc) ยท 822 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
/**
* Missing Number
* 0๋ถํฐ n๊น์ง์ ์ซ์ ์ค ํ๋๊ฐ ๋น ์ง ๋ฐฐ์ด์์ ๋๋ฝ๋ ์ซ์ ์ฐพ๊ธฐ
*/
// ํ์ด 1: ํฉ ๊ณต์ ์ด์ฉ
// ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(1)
// 0๋ถํฐ n๊น์ง์ ํฉ์์ ๋ฐฐ์ด ์์๋ค์ ํฉ์ ๋นผ๋ฉด ๋น ์ง ์ซ์๊ฐ ๋์จ๋ค
const missingNumber = (nums) => {
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2; // ๋ฑ์ฐจ์์ด ํฉ ๊ณต์
const actualSum = nums.reduce((sum, num) => sum + num, 0);
return expectedSum - actualSum;
};
// ํ์ด 2: Set ์ฌ์ฉ
// ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(n)
// Set์ ๋ฃ๊ณ 0๋ถํฐ n๊น์ง ์ํํ๋ฉด์ ์๋ ์ซ์ ์ฐพ๊ธฐ
const missingNumberSet = (nums) => {
const numSet = new Set(nums);
for (let i = 0; i <= nums.length; i++) {
if (!numSet.has(i)) {
return i;
}
}
};