File tree Expand file tree Collapse file tree 1 file changed +8
-9
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +8
-9
lines changed Original file line number Diff line number Diff line change 22 * @param {number[] } nums
33 * @return {number }
44 */
5+
56var longestConsecutive = function ( nums ) {
67 const numSet = new Set ( nums ) ;
78
89 let maxLength = 0 ;
910 let currentLength = 0 ;
1011
11- nums . forEach ( num => {
12+ const countConsecutive = ( num , step ) => {
1213 let currentNum = num ;
1314 while ( numSet . has ( currentNum ) ) {
14- numSet . delete ( currentNum )
15- currentNum += 1 ;
15+ numSet . delete ( currentNum ) ;
16+ currentNum += step ;
1617 currentLength += 1 ;
1718 }
19+ }
1820
19- currentNum = num - 1 ;
20- while ( numSet . has ( currentNum ) ) {
21- numSet . delete ( currentNum )
22- currentNum -= 1 ;
23- currentLength += 1 ;
24- }
21+ nums . forEach ( num => {
22+ countConsecutive ( num , 1 ) ;
23+ countConsecutive ( num - 1 , - 1 ) ;
2524
2625 maxLength = Math . max ( maxLength , currentLength ) ;
2726 currentLength = 0 ;
You can’t perform that action at this time.
0 commit comments