File tree Expand file tree Collapse file tree 1 file changed +14
-17
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +14
-17
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
- *
3
2
* 연속된 숫자의 최대 길이를 구하는 문제
4
3
* @param {number[] } nums
5
4
* @return {number }
9
8
* nums 배열을 중복을 제거하고 오름차순으로 정렬한다.
10
9
* 중복을 제거하고 정렬한 배열을 순회하면서 연속된 숫자의 길이를 구한다.
11
10
*/
12
-
13
11
function longestConsecutive ( nums : number [ ] ) : number {
14
12
if ( nums . length === 0 ) return 0 ;
15
- const sortNum = Array . from ( new Set ( nums ) ) . sort ( ( a , b ) => a - b ) ;
13
+ const sortedNums = Array . from ( new Set ( nums ) ) . sort ( ( a , b ) => a - b ) ;
16
14
17
- if ( sortNum . length === 1 ) return 1 ;
15
+ if ( sortedNums . length === 1 ) return 1 ;
18
16
19
- const resultArray : number [ ] = [ ]
20
- let count = 1 ;
17
+ let currentCount = 1 ;
18
+ let maxCount = 1 ;
21
19
22
- for ( let i = 0 ; i < sortNum . length - 1 ; i ++ ) {
23
- const prevNum = sortNum [ i ] ;
24
- const nextNum = sortNum [ i + 1 ] ;
20
+ for ( let i = 0 ; i < sortedNums . length - 1 ; i ++ ) {
21
+ const currentNum = sortedNums [ i ] ;
22
+ const nextNum = sortedNums [ i + 1 ] ;
25
23
26
- if ( prevNum + 1 === nextNum ) {
27
- count ++ ;
28
- } else {
29
- resultArray . push ( count )
30
- count = 1 ;
24
+ if ( currentNum + 1 === nextNum ) {
25
+ currentCount ++ ;
26
+ maxCount = Math . max ( maxCount , currentCount ) ;
27
+ } else {
28
+ currentCount = 1 ;
31
29
}
32
30
}
33
- resultArray . push ( count ) ;
34
31
35
- return resultArray . length > 0 ? Math . max ( ... resultArray ) : 1 ;
36
- } ;
32
+ return maxCount ;
33
+ }
You can’t perform that action at this time.
0 commit comments