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 3
3
* @return {number }
4
4
*/
5
5
var longestConsecutive = function ( nums ) {
6
- if ( nums . length === 0 ) return 0 ;
6
+ if ( nums . length === 0 ) return nums . length ;
7
7
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 ) ;
15
10
16
- // ์ฐ์๋ ์ซ์ ์ฐพ๊ธฐ
17
- while ( numSet . has ( currentNum + 1 ) ) {
18
- currentNum ++ ;
19
- count ++ ;
20
- }
11
+ let longest = 1 ;
12
+ let currentlength = 1 ;
21
13
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 ;
23
20
}
24
21
}
25
-
26
22
return longest ;
27
23
} ;
You canโt perform that action at this time.
0 commit comments