forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocow.py
More file actions
44 lines (33 loc) ยท 1.09 KB
/
socow.py
File metadata and controls
44 lines (33 loc) ยท 1.09 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
268. Missing Number
๋ฌธ์ ์์ฝ
- 0๋ถํฐ n๊น์ง์ ์ซ์ ์ค ํ๋๊ฐ ๋น ์ง ๋ฐฐ์ด์ด ์ฃผ์ด์ง
- ๋น ์ง ์ซ์ ์ฐพ๊ธฐ!
- ์: [3, 0, 1] โ 2๊ฐ ์์ โ ๋ต: 2
๋ฌธ์ ์์
nums = [3, 0, 1] (0, 1, 2, 3 ์ค ํ๋ ๋น ์ง)
โ 2๊ฐ ์์!
โ return 2
ํต์ฌ ์๊ณ ๋ฆฌ์ฆ
- ์๊ฐ๋ณต์ก๋: O(n)
- ๊ณต๊ฐ๋ณต์ก๋: O(1)
ํต์ฌ ์์ด๋์ด
- ์ํ: 0~n ํฉ๊ณ - ๋ฐฐ์ด ํฉ๊ณ = ๋น ์ง ์ซ์!
- XOR: ๊ฐ์ ์ซ์ XORํ๋ฉด 0, ๋จ๋ ๊ฒ ๋น ์ง ์ซ์!
"""
from typing import List
# ๋ฐฉ๋ฒ 1: ์ํ (๊ฐ์ฅ ์ง๊ด์ !)
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
expected_sum = n * (n + 1) // 2 # 0~n ํฉ๊ณ ๊ณต์
actual_sum = sum(nums) # ์ค์ ํฉ๊ณ
return expected_sum - actual_sum
# ๋ฐฉ๋ฒ 2: XOR (๋นํธ ์ฐ์ฐ)
class SolutionXOR:
def missingNumber(self, nums: List[int]) -> int:
result = len(nums) # n๋ถํฐ ์์
for i, num in enumerate(nums):
result ^= i # ์ธ๋ฑ์ค๋ XOR
result ^= num # ๊ฐ์ด๋ XOR
return result