File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[] } nums
3+ * @return {number }
4+ */
5+ var longestConsecutive = function ( nums ) {
6+ // ์ฒซ ๋ฒ์งธ ์ ๋ ฌ์ ํ๋ค.
7+ if ( nums . length === 0 ) {
8+ return 0 ;
9+ }
10+
11+ nums . sort ( ( a , b ) => a - b ) ; // ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ
12+ console . log ( nums ) ;
13+
14+ // ๋ ๋ฒ์งธ ์ซ์๊ฐ 1์ฉ ๊ณ์ํด์ ์ฆ๊ฐํ๋ ๊ตฌ๊ฐ์ ์ฐพ๋๋ค.
15+ let longest = 0 ;
16+ let length = 1 ;
17+
18+ for ( let i = 0 ; i < nums . length - 1 ; i ++ ) {
19+ if ( nums [ i ] === nums [ i + 1 ] ) {
20+ continue ;
21+ }
22+ // ์ฐ์ํด์ 1์ฉ ์ฆ๊ฐํ๋ ๊ตฌ๊ฐ ์ฐพ๊ธฐ
23+ if ( nums [ i + 1 ] - nums [ i ] === 1 ) {
24+ length += 1 ;
25+ } else {
26+ longest = Math . max ( longest , length ) ;
27+ length = 1 ;
28+ }
29+ }
30+ return Math . max ( longest , length ) ;
31+ } ;
32+
33+ // ์๊ฐ๋ณต์ก๋์ ๊ณต๊ฐ๋ณต์ก๋
34+ // ์๊ฐ๋ณต์ก๋: ์ ๋ ฌ ์ฌ์ฉ(O(nlogn)) + for๋ฌธ์ผ๋ก ๋ฐฐ์ด ํ์(O(n)) = O(nlogn)
35+ // ๊ณต๊ฐ๋ณต์ก๋: O(1)
You canโt perform that action at this time.
0 commit comments