File tree Expand file tree Collapse file tree 1 file changed +11
-15
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +11
-15
lines changed Original file line number Diff line number Diff line change 33 * @return {number }
44 */
55var longestConsecutive = function ( nums ) {
6- if ( nums . length === 0 ) return 0 ;
6+ if ( nums . length === 0 ) return nums . length ;
77
8- const numSet = new Set ( nums ) ;
9- let longest = 0 ;
10- for ( let num of numSet ) {
11- // `num - 1`์ด ์์ผ๋ฉด ์๋ก์ด ์์ด์ ์์์
12- if ( ! numSet . has ( num - 1 ) ) {
13- let count = 1 ;
14- let currentNum = num ;
8+ const setNums = new Set ( nums ) ;
9+ const sortNums = [ ...setNums ] . sort ( ( a , b ) => a - b ) ;
1510
16- // ์ฐ์๋ ์ซ์ ์ฐพ๊ธฐ
17- while ( numSet . has ( currentNum + 1 ) ) {
18- currentNum ++ ;
19- count ++ ;
20- }
11+ let longest = 1 ;
12+ let currentlength = 1 ;
2113
22- longest = Math . max ( longest , count ) ;
14+ for ( let i = 0 ; i < sortNums . length ; i ++ ) {
15+ if ( sortNums [ i ] + 1 === sortNums [ i + 1 ] ) {
16+ currentlength ++ ;
17+ longest = Math . max ( longest , currentlength ) ;
18+ } else {
19+ currentlength = 1 ;
2320 }
2421 }
25-
2622 return longest ;
2723} ;
You canโt perform that action at this time.
0 commit comments