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+ /**
2+ * ์ฃผ์ด์ง ์ซ์ ๋ฐฐ์ด์์ ๊ฐ์ฅ ๊ธด ์ฐ์๋ ์์ด์ ๊ธธ์ด๋ฅผ ์ฐพ๋๋ค.
3+ * ์๊ฐ๋ณต์ก๋: O(n)
4+ * ์ด์ : ๊ฐ ์ซ์๋ ์ต๋ ํ ๋ฒ๋ง ์์์ ์ผ๋ก ๊ฒ์ฌ๋๊ณ ,
5+ * ์ฐ์ ์์ด ํ์๋ ์ค๋ณต ์์ด ์งํ๋๋ค.
6+ *
7+ * @param {number[] } nums
8+ * @return {number }
9+ */
10+ var longestConsecutive = function ( nums ) {
11+
12+ // ๋ฐฐ์ด์ Set์ผ๋ก ๋ณํ
13+ const numSet = new Set ( nums ) ;
14+
15+ // ๊ฐ์ฅ ๊ธด ์ฐ์ ๊ธธ์ด๋ฅผ ์ ์ฅ
16+ let longest = 0 ;
17+ // Set์ ์ํ
18+ for ( let n of numSet ) {
19+ // ํ์ฌ ์ซ์๊ฐ ์ฐ์ ์์ด์ "์์์ "์ธ์ง ํ์ธ
20+ // n-1 ์ด ์กด์ฌํ๋ฉด ์ด๋ฏธ ์์ ์ ์์ด ์กด์ฌํจ
21+ if ( ! numSet . has ( n - 1 ) ) {
22+
23+ // ์์ํ๋ ์์ด ๊ธธ์ด
24+ let length = 1 ;
25+
26+ // ๊ณ์ ์กด์ฌํ๋์ง ํ์ธ
27+ while ( numSet . has ( n + length ) ) {
28+ length ++ ;
29+ }
30+ // ์ง๊ธ๊น์ง ์ฐพ์ ์ต๋ ๊ธธ์ด ๊ฐฑ์
31+ longest = Math . max ( longest , length ) ;
32+ }
33+ }
34+ return longest ;
35+ } ;
You canโt perform that action at this time.
0 commit comments