Skip to content

Commit 931bcdf

Browse files
authored
Merge pull request #2292 from leehyeyun/main
[leehyeyun] WEEK 11 solutions
2 parents e7c2fad + 3bc68f1 commit 931bcdf

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
/*
6+
๋ฌธ์ œ๋ช…: Missing Number (LeetCode 268)
7+
8+
๋ฌธ์ œ ์„ค๋ช…:
9+
๊ธธ์ด๊ฐ€ n์ธ ๋ฐฐ์—ด nums๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.
10+
์ด ๋ฐฐ์—ด์—๋Š” 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ˆซ์ž ์ค‘์—์„œ
11+
์ •ํ™•ํžˆ ํ•˜๋‚˜๋ฅผ ์ œ์™ธํ•œ n๊ฐœ์˜ ์ˆซ์ž๊ฐ€ ๋“ค์–ด ์žˆ๋‹ค.
12+
(์ฆ‰, ์›๋ž˜๋Š” n+1๊ฐœ์˜ ์ˆซ์ž๊ฐ€ ์žˆ์–ด์•ผ ํ•จ)
13+
14+
๋ชฉํ‘œ:
15+
0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ๋ฒ”์œ„ ์•ˆ์—์„œ
16+
๋ฐฐ์—ด nums์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” "๋‹จ ํ•˜๋‚˜์˜ ์ˆซ์ž"๋ฅผ ์ฐพ์•„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
17+
18+
์ž…๋ ฅ ์กฐ๊ฑด:
19+
- nums.length == n
20+
- 1 <= n <= 10^4
21+
- nums[i]๋Š” 0 ์ด์ƒ n ์ดํ•˜์˜ ์ •์ˆ˜
22+
- nums ์•ˆ์˜ ๋ชจ๋“  ๊ฐ’์€ ์„œ๋กœ ๋‹ค๋ฅด๋‹ค (์ค‘๋ณต ์—†์Œ)
23+
24+
์ถœ๋ ฅ:
25+
- nums ๋ฐฐ์—ด์— ์—†๋Š” ์ˆซ์ž 1๊ฐœ๋ฅผ ๋ฐ˜ํ™˜
26+
27+
ํ•ต์‹ฌ ํฌ์ธํŠธ:
28+
- ์ •์ƒ ์ƒํƒœ๋ผ๋ฉด ์ˆซ์ž ๋ฒ”์œ„๋Š” [0, n] (์ด n+1๊ฐœ)
29+
- ์‹ค์ œ ๋ฐฐ์—ด์—๋Š” n๊ฐœ๋งŒ ์กด์žฌ โ†’ ๋ฐ˜๋“œ์‹œ ํ•˜๋‚˜๋Š” ๋น ์ ธ ์žˆ์Œ
30+
- ๋ฐฐ์—ด์€ ์ •๋ ฌ๋˜์–ด ์žˆ์ง€ ์•Š์Œ
31+
32+
์˜ˆ์‹œ 1:
33+
์ž…๋ ฅ: nums = [3, 0, 1]
34+
ํ•ด์„:
35+
n = 3
36+
์ •์ƒ ๋ฒ”์œ„: [0, 1, 2, 3]
37+
๋น ์ง„ ์ˆซ์ž: 2
38+
์ถœ๋ ฅ: 2
39+
40+
์˜ˆ์‹œ 2:
41+
์ž…๋ ฅ: nums = [0, 1]
42+
ํ•ด์„:
43+
n = 2
44+
์ •์ƒ ๋ฒ”์œ„: [0, 1, 2]
45+
๋น ์ง„ ์ˆซ์ž: 2
46+
์ถœ๋ ฅ: 2
47+
48+
์˜ˆ์‹œ 3:
49+
์ž…๋ ฅ: nums = [9,6,4,2,3,5,7,0,1]
50+
ํ•ด์„:
51+
n = 9
52+
์ •์ƒ ๋ฒ”์œ„: [0, 1, 2, ..., 9]
53+
๋น ์ง„ ์ˆซ์ž: 8
54+
์ถœ๋ ฅ: 8
55+
56+
์ถ”๊ฐ€ ์š”๊ตฌ์‚ฌํ•ญ (Follow up):
57+
- ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
58+
โ†’ ๋ฐฐ์—ด์„ ํ•œ ๋ฒˆ๋งŒ ์ˆœํšŒํ•ด์•ผ ํ•จ
59+
- ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
60+
โ†’ ์ถ”๊ฐ€ ๋ฐฐ์—ด, ํ•ด์‹œ๋งต ๋“ฑ ์‚ฌ์šฉ ๋ถˆ๊ฐ€
61+
62+
๋ฌธ์ œ ์˜๋„:
63+
- ๋‹จ์ˆœ ํƒ์ƒ‰์ด ์•„๋‹ˆ๋ผ
64+
"์ „์ฒด ๋ฒ”์œ„์˜ ์„ฑ์งˆ"์„ ์ด์šฉํ•ด
65+
๋น ์ง„ ์ˆซ์ž๋ฅผ ์ฐพ์•„๋‚ผ ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธ
66+
- ์ˆ˜ํ•™์  ์‚ฌ๊ณ  ๋˜๋Š” ๋น„ํŠธ ์—ฐ์‚ฐ์  ์‚ฌ๊ณ ๋ฅผ ์š”๊ตฌํ•˜๋Š” ๋ฌธ์ œ
67+
*/
68+
var missingNumber = function(nums) {
69+
const n = nums.length;
70+
71+
const expectedSum = (n * (n + 1)) / 2;
72+
73+
let actualSum = 0;
74+
for (let i = 0; i < n; i++) {
75+
actualSum += nums[i];
76+
}
77+
78+
return expectedSum - actualSum;
79+
};
80+
81+
console.log(missingNumber([3, 0, 1]))
82+
console.log(missingNumber([0, 1]))
83+
console.log(missingNumber([9,6,4,2,3,5,7,0,1]))
84+

0 commit comments

Comments
ย (0)