File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * Missing Number
3+ * 0๋ถํฐ n๊น์ง์ ์ซ์ ์ค ํ๋๊ฐ ๋น ์ง ๋ฐฐ์ด์์ ๋๋ฝ๋ ์ซ์ ์ฐพ๊ธฐ
4+ */
5+
6+ // ํ์ด 1: ํฉ ๊ณต์ ์ด์ฉ
7+ // ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(1)
8+ // 0๋ถํฐ n๊น์ง์ ํฉ์์ ๋ฐฐ์ด ์์๋ค์ ํฉ์ ๋นผ๋ฉด ๋น ์ง ์ซ์๊ฐ ๋์จ๋ค
9+ const missingNumber = ( nums ) => {
10+ const n = nums . length ;
11+ const expectedSum = ( n * ( n + 1 ) ) / 2 ; // ๋ฑ์ฐจ์์ด ํฉ ๊ณต์
12+ const actualSum = nums . reduce ( ( sum , num ) => sum + num , 0 ) ;
13+ return expectedSum - actualSum ;
14+ } ;
15+
16+ // ํ์ด 2: Set ์ฌ์ฉ
17+ // ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(n)
18+ // Set์ ๋ฃ๊ณ 0๋ถํฐ n๊น์ง ์ํํ๋ฉด์ ์๋ ์ซ์ ์ฐพ๊ธฐ
19+ const missingNumberSet = ( nums ) => {
20+ const numSet = new Set ( nums ) ;
21+
22+ for ( let i = 0 ; i <= nums . length ; i ++ ) {
23+ if ( ! numSet . has ( i ) ) {
24+ return i ;
25+ }
26+ }
27+ } ;
You canโt perform that action at this time.
0 commit comments