Skip to content

Commit def85b8

Browse files
committed
refactor longest-consecutive-sequence
1 parent a682075 commit def85b8

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed
Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
/**
2-
*
32
* 연속된 숫자의 최대 길이를 구하는 문제
43
* @param {number[]} nums
54
* @return {number}
@@ -9,28 +8,26 @@
98
* nums 배열을 중복을 제거하고 오름차순으로 정렬한다.
109
* 중복을 제거하고 정렬한 배열을 순회하면서 연속된 숫자의 길이를 구한다.
1110
*/
12-
1311
function 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+
}

0 commit comments

Comments
 (0)