Skip to content

Commit b1bc659

Browse files
committed
268. Missing Number
1 parent 3a695f4 commit b1bc659

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

โ€Žmissing-number/socow.pyโ€Ž

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
268. Missing Number
3+
4+
๋ฌธ์ œ ์š”์•ฝ
5+
- 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ˆซ์ž ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋น ์ง„ ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง
6+
- ๋น ์ง„ ์ˆซ์ž ์ฐพ๊ธฐ!
7+
- ์˜ˆ: [3, 0, 1] โ†’ 2๊ฐ€ ์—†์Œ โ†’ ๋‹ต: 2
8+
9+
๋ฌธ์ œ ์˜ˆ์‹œ
10+
nums = [3, 0, 1] (0, 1, 2, 3 ์ค‘ ํ•˜๋‚˜ ๋น ์ง)
11+
โ†’ 2๊ฐ€ ์—†์Œ!
12+
โ†’ return 2
13+
14+
ํ•ต์‹ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜
15+
- ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
16+
- ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
17+
18+
ํ•ต์‹ฌ ์•„์ด๋””์–ด
19+
- ์ˆ˜ํ•™: 0~n ํ•ฉ๊ณ„ - ๋ฐฐ์—ด ํ•ฉ๊ณ„ = ๋น ์ง„ ์ˆซ์ž!
20+
- XOR: ๊ฐ™์€ ์ˆซ์ž XORํ•˜๋ฉด 0, ๋‚จ๋Š” ๊ฒŒ ๋น ์ง„ ์ˆซ์ž!
21+
"""
22+
23+
from typing import List
24+
25+
26+
# ๋ฐฉ๋ฒ• 1: ์ˆ˜ํ•™ (๊ฐ€์žฅ ์ง๊ด€์ !)
27+
class Solution:
28+
def missingNumber(self, nums: List[int]) -> int:
29+
n = len(nums)
30+
expected_sum = n * (n + 1) // 2 # 0~n ํ•ฉ๊ณ„ ๊ณต์‹
31+
actual_sum = sum(nums) # ์‹ค์ œ ํ•ฉ๊ณ„
32+
return expected_sum - actual_sum
33+
34+
35+
# ๋ฐฉ๋ฒ• 2: XOR (๋น„ํŠธ ์—ฐ์‚ฐ)
36+
class SolutionXOR:
37+
def missingNumber(self, nums: List[int]) -> int:
38+
result = len(nums) # n๋ถ€ํ„ฐ ์‹œ์ž‘
39+
40+
for i, num in enumerate(nums):
41+
result ^= i # ์ธ๋ฑ์Šค๋ž‘ XOR
42+
result ^= num # ๊ฐ’์ด๋ž‘ XOR
43+
44+
return result

0 commit comments

Comments
ย (0)