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 11/**
2- *
32 * 연속된 숫자의 최대 길이를 구하는 문제
43 * @param {number[] } nums
54 * @return {number }
98 * nums 배열을 중복을 제거하고 오름차순으로 정렬한다.
109 * 중복을 제거하고 정렬한 배열을 순회하면서 연속된 숫자의 길이를 구한다.
1110 */
12-
1311function longestConsecutive ( nums : number [ ] ) : number {
1412 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 ) ;
1614
17- if ( sortNum . length === 1 ) return 1 ;
15+ if ( sortedNums . length === 1 ) return 1 ;
1816
19- const resultArray : number [ ] = [ ]
20- let count = 1 ;
17+ let currentCount = 1 ;
18+ let maxCount = 1 ;
2119
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 ] ;
2523
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 ;
3129 }
3230 }
33- resultArray . push ( count ) ;
3431
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