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 2
2
* @param {number[] } nums
3
3
* @return {number }
4
4
*/
5
+
5
6
var longestConsecutive = function ( nums ) {
6
7
const numSet = new Set ( nums ) ;
7
8
8
9
let maxLength = 0 ;
9
10
let currentLength = 0 ;
10
11
11
- nums . forEach ( num => {
12
+ const countConsecutive = ( num , step ) => {
12
13
let currentNum = num ;
13
14
while ( numSet . has ( currentNum ) ) {
14
- numSet . delete ( currentNum )
15
- currentNum += 1 ;
15
+ numSet . delete ( currentNum ) ;
16
+ currentNum += step ;
16
17
currentLength += 1 ;
17
18
}
19
+ }
18
20
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 ) ;
25
24
26
25
maxLength = Math . max ( maxLength , currentLength ) ;
27
26
currentLength = 0 ;
You can’t perform that action at this time.
0 commit comments