File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * λ¬Έμ μ€λͺ
3
+ * - 0λΆν° nκΉμ§ μ«μκ° μ€λ³΅ μμ΄ λ¨ νλλ§ λΉ μ Έμλ μ«μ μ°ΎκΈ°
4
+ *
5
+ * μμ΄λμ΄
6
+ * 1) μ²΄ν¬ λ°°μ΄ μμ±
7
+ * - 0λΆν° nκΉμ§ μ«μκ° μ€λ³΅ μμ΄ λ¨ νλλ§ λΉ μ Έμλ μ«μ μ°ΎκΈ°
8
+ *
9
+ * 2) μνμ μ κ·Ό
10
+ * - n*(n+1)/2: λ°°μ΄μ ν© - μ£Όμ΄μ§ λ°°μ΄μ ν© = λΉ μ§ μ«μ
11
+ *
12
+ * 3) XOR νμ©
13
+ * - 0 ^ 1 ^ 2 ^ ... ^ n : λͺ¨λ μ«μ XOR
14
+ * - nums[0] ^ nums[1] ^ ... ^ nums[n-1] : λ°°μ΄ λ΄ μ‘΄μ¬νλ μ«μλ€ XOR
15
+ * - μ΄ λμ XORνλ©΄, μ€λ³΅λλ μ«μλ λͺ¨λ μμλμ΄ λΉ μ§ μ«μλ§ λ¨μ.
16
+ */
17
+
18
+ function missingNumber ( nums : number [ ] ) : number {
19
+ const check = new Array ( nums . length ) . fill ( false ) ;
20
+
21
+ nums . forEach ( ( num ) => ( check [ num ] = true ) ) ;
22
+
23
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
24
+ if ( ! check [ i ] ) return i ;
25
+ }
26
+ return nums . length ;
27
+ }
28
+
29
+ // μνμ μ κ·Ό
30
+ function missingNumber2 ( nums : number [ ] ) : number {
31
+ const n = nums . length ;
32
+ const expectedSum = ( n * ( n + 1 ) ) / 2 ;
33
+ const actualSum = nums . reduce ( ( acc , cur ) => acc + cur , 0 ) ;
34
+ return expectedSum - actualSum ;
35
+ }
36
+
37
+ // XOR νμ©
38
+ function missingNumber3 ( nums : number [ ] ) : number {
39
+ let xor = 0 ;
40
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
41
+ xor ^= i ^ nums [ i ] ;
42
+ }
43
+
44
+ return xor ^ nums . length ;
45
+ }
You canβt perform that action at this time.
0 commit comments