File tree Expand file tree Collapse file tree
longest-consecutive-sequence Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // nums ์์ ์์์ ์๊ด์์ด ๊ฐ์ฅ ๊ธธ๊ฒ ์ด์ ์ ์๋ ์ฐ์๋ ์ซ์์ ์นด์ดํธ
2+ // Constraints : Time complexity O(n)
3+
4+ // 1๋ฒ์งธ ์๋
5+ /*
6+ 1. O(n)์ด ๋๋๋ก ์ ๋ ฌํ๋ค.
7+ -> ์ด์ฐจํผ ์ ์ฒด ์๊ฐ๋ณต์ก๋๊ฐ O(n)์ด ๋ ๊ฑฐ๊ธฐ ๋๋ฌธ์, ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ์ ๊ทธ๋ณด๋ค ๋นจ๋ผ๋ ๋๋ค.
8+ -> ๊ทผ๋ฐ ๋ค์๋ณด๋ nums ์ nums[i]์ ๊ธธ์ด๊ฐ -10^9 ~ 10^9 ๊ฐ ๋ ์ ์๊ธฐ ๋๋ฌธ์ ์ ๋ ฌ๋ก ํธ๋๊ฒ ๋ง์ง ์์ ์๋ ์๋ค.
9+ 2. ์ ๋ ฌ๋ ๋ฐฐ์ด์ ์์ฐจ์ ์ผ๋ก ๋๋ฉด์ ์ด์ด์ง ๋ ์นด์ดํธ๋ฅผ ํ๋ค.
10+ 3. ์ซ์๊ฐ ๋ฌ๋ผ์ง ๋ ์นด์ดํธ๋ฅผ ๋ค์ ์ด๊ธฐํํ๊ณ , ์ด์ ๊ฐ๋ณด๋ค ๋์์ง ๋๋ง๋ค max ๋ฅผ ๊ฐฑ์
11+ 4. ์ต์ข
max ๊ฐ์ ๋ฐํํ๋ค.
12+ */
13+
14+ // 2๋ฒ์งธ ์๋
15+ /*
16+ 1. nums ๋ฐฐ์ด์ set์ผ๋ก ๋ง๋ ๋ค.
17+ 2. set์์ ๊ฐ์ ํ๋์ฉ ์ํํ๋ค.
18+ 3. ์ฌ๊ธฐ์ ์ด๋ป๊ฒ ํด์ผํ์ง..? (๋งํ์ ai ์๊ฒ ๋์์ ์์ฒญํจ.)
19+ */
20+
21+ function longestConsecutive ( nums : number [ ] ) : number {
22+ const numSet = new Set ( nums ) ;
23+ let max = 0 ;
24+ for ( const num of numSet ) {
25+ if ( ! numSet . has ( num - 1 ) ) {
26+ let curNum = num ;
27+ let curLen = 1 ;
28+
29+ while ( numSet . has ( curNum + 1 ) ) {
30+ curNum ++ ;
31+ curLen ++ ;
32+ }
33+
34+ max = Math . max ( max , curLen ) ;
35+ }
36+ }
37+
38+ return max ;
39+ }
You canโt perform that action at this time.
0 commit comments