Skip to content

Commit 2b4df39

Browse files
authored
longest-consecutive-sequence solution
1 parent f804393 commit 2b4df39

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
function longestConsecutive(nums: number[]): number {
2+
// 첫 시도: sort때문에 시간 복잡도가 O(n log n)라 O(n)에 풀어야 한다는 요구사항 만족하지 못함, 공간복잡도는 O(n)
3+
// if (nums.length === 0) return 0;
4+
// const sorted = [...new Set(nums)].sort((a, b) => a-b);
5+
// let max = 1;
6+
// let current = 1;
7+
8+
// for (let i=0; i<nums.length; i++) {
9+
// console.log(sorted[i])
10+
// if (sorted[i+1] - sorted[i] === 1) {
11+
// current += 1;
12+
// } else {
13+
// current = 1;
14+
// }
15+
16+
// max = Math.max(max, current);
17+
// }
18+
19+
// return max;
20+
21+
// 두번째 시도: 시간, 공간복잡도 O(n)
22+
if (nums.length === 0) return 0;
23+
24+
const numSet = new Set(nums);
25+
let current = 0;
26+
let consecutive = 1;
27+
let max = 1;
28+
29+
for (let num of numSet) {
30+
if (!numSet.has(num - 1)) {
31+
current = num;
32+
consecutive = 1;
33+
34+
while (numSet.has(current + 1)) {
35+
consecutive += 1;
36+
current = current + 1;
37+
}
38+
39+
max = Math.max(consecutive, max);
40+
}
41+
}
42+
43+
return max;
44+
};

0 commit comments

Comments
 (0)