Skip to content

Commit d26750f

Browse files
committed
solve(w11): 268. Missing Number
1 parent 028dd0f commit d26750f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# https://leetcode.com/problems/missing-number/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def missingNumber_math(self, nums: List[int]) -> int:
7+
"""
8+
[Complexity]
9+
- TC: O(n) (sum(nums))
10+
- SC: O(1)
11+
12+
[Approach]
13+
์ˆ˜ํ•™์ ์œผ๋กœ ์ƒ๊ฐํ•ด๋ณด๋ฉด, missing number๋Š” (0 ~ n๊นŒ์ง€ ๊ฐ’์˜ ํ•ฉ) - (nums์˜ ํ•ฉ)์ด ๋œ๋‹ค.
14+
"""
15+
# (sum of [0, n]) - (sum(nums))
16+
n = len(nums)
17+
return n * (n + 1) // 2 - sum(nums)
18+
19+
def missingNumber(self, nums: List[int]) -> int:
20+
"""
21+
[Complexity]
22+
- TC: O(n)
23+
- SC: O(1)
24+
25+
[Approach]
26+
bit manipulation ๊ด€์ ์œผ๋กœ ์ ‘๊ทผํ•ด๋ณด๋ฉด, missing number๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ๊ฐ’์€ ๋‹ค์Œ ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ์—์„œ ๋ชจ๋‘ ๋ฐœ๊ฒฌ๋œ๋‹ค.
27+
(1) 0 ~ n๊นŒ์ง€์˜ ๊ฐ’
28+
(2) nums์˜ ์›์†Œ
29+
missing number๋Š” ์ด ๋‘ ๊ฐ€์ง€ ์ผ€์ด์Šค ์ค‘ (1)์—์„œ๋งŒ ํ•œ ๋ฒˆ ๋ฐœ๊ฒฌ๋˜๋ฏ€๋กœ, ์ด๋ฅผ XOR ์—ฐ์‚ฐ์œผ๋กœ ๊ฒ€์ถœํ•ด ๋‚ผ ์ˆ˜ ์žˆ๋‹ค.
30+
(์ง์ˆ˜ ๋ฒˆ ๋“ฑ์žฅํ•œ ๊ฐ’์€ ์‚ฌ๋ผ์ง)
31+
"""
32+
33+
res = 0
34+
35+
# (1) 0 ~ n๊นŒ์ง€์˜ ๊ฐ’ XOR
36+
for i in range(len(nums) + 1):
37+
res ^= i
38+
# (2) nums์˜ ์›์†Œ XOR
39+
for n in nums:
40+
res ^= n
41+
42+
return res

0 commit comments

Comments
ย (0)