Skip to content

Commit dce519d

Browse files
committed
solve: longest-consecutive-sequence2 개선 문제 풀이 추가
1 parent 8e22356 commit dce519d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

longest-consecutive-sequence/reach0908.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,40 @@ const longestConsecutive = function (nums) {
2929

3030
return maxConsecutiveCount;
3131
};
32+
33+
/**
34+
* @description
35+
* time complexity: O(n)
36+
* space complexity: O(n)
37+
* runtime: 36ms
38+
* 풀이 방법: 중복을 제거하고 Set을 사용하여 O(1) 조회 가능하도록 한 다음에 연속된 숫자의 개수를 카운트하여 최대값을 반환한다.
39+
* @param {number[]} nums
40+
* @return {number}
41+
*/
42+
const longestConsecutive2 = function (nums) {
43+
if (nums.length === 0) return 0;
44+
45+
// Set을 사용하여 O(1) 조회 가능
46+
const numSet = new Set(nums);
47+
let maxLength = 0;
48+
49+
for (const num of numSet) {
50+
// 현재 숫자가 연속 수열의 시작점인지 확인
51+
// num-1이 존재하지 않으면 num이 시작점
52+
if (!numSet.has(num - 1)) {
53+
let currentNum = num;
54+
let currentLength = 1;
55+
56+
// 연속된 다음 숫자들이 존재하는 동안 계속 탐색
57+
while (numSet.has(currentNum + 1)) {
58+
currentNum += 1;
59+
currentLength += 1;
60+
}
61+
62+
// 최대 길이 업데이트
63+
maxLength = Math.max(maxLength, currentLength);
64+
}
65+
}
66+
67+
return maxLength;
68+
};

0 commit comments

Comments
 (0)