Skip to content

Commit a3db8f6

Browse files
author
jaehyunglee
committed
longest-consecutive-sequence solution
1 parent 9f3340b commit a3db8f6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* @param nums - 정렬되지 않은 정수 배열
3+
* @returns - 가장 긴 연속 요소 길이
4+
*
5+
* @description
6+
* 1. 객체의 정렬 활용 방식 - O(n log n) -> 결국 key 정렬 시 n log n 발생
7+
* 2. 정렬 없이 key find 방식 - O(n) -> 시작점일 경우만 판단, 모든 num에 대해 돌지 않음
8+
*/
9+
10+
// function longestConsecutive(nums: number[]): number {
11+
// const obj = nums.reduce((acc, cur) => {
12+
// acc[cur] = (acc[cur] || 0) + 1;
13+
// return acc;
14+
// }, {});
15+
// let cnt = 1;
16+
// let answer = 0;
17+
18+
// const keys = Object.keys(obj);
19+
20+
// for (let i = 1; i < keys.length; i++) {
21+
// if (Number(keys[i]) === Number(keys[i - 1]) + 1) {
22+
// cnt++;
23+
// } else {
24+
// answer = Math.max(answer, cnt);
25+
// cnt = 1;
26+
// }
27+
// }
28+
29+
// answer = Math.max(answer, cnt);
30+
31+
// return answer;
32+
// }
33+
34+
function longestConsecutive(nums: number[]): number {
35+
const numSet = new Set(nums);
36+
let answer = 0;
37+
38+
for (const num of numSet) {
39+
if (!numSet.has(num - 1)) {
40+
let current = num;
41+
let cnt = 1;
42+
43+
while (numSet.has(current + 1)) {
44+
current++;
45+
cnt++;
46+
}
47+
48+
answer = Math.max(answer, cnt);
49+
}
50+
}
51+
return answer;
52+
}

0 commit comments

Comments
 (0)