File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
You canโt perform that action at this time.
0 commit comments