Skip to content

Commit 22f71ca

Browse files
committed
feat(soobing): week1 > longest-consecutive-sequence
1 parent 632770a commit 22f71ca

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* 문제 유형: 그래프(Union Find)
3+
*
4+
* 문제 설명
5+
* - 주어진 배열에서 가장 긴 연속된 수열의 길이를 구하는 문제
6+
*
7+
* 아이디어
8+
* 1) 중복된 수 제거 후 순회하며 값이 1차이 나는 항목끼리 합집합 만들기
9+
*
10+
* 미션
11+
* - 더 빠른 풀이: HashSet 기반 Greedy로 풀어보기.
12+
*
13+
*/
14+
class UnionFind {
15+
parent: Map<number, number> = new Map();
16+
size: Map<number, number> = new Map();
17+
18+
constructor(nums: number[]) {
19+
for (const num of nums) {
20+
this.parent.set(num, num);
21+
this.size.set(num, 1);
22+
}
23+
}
24+
25+
find(x: number): number {
26+
if (this.parent.get(x) !== x) {
27+
this.parent.set(x, this.find(this.parent.get(x)!));
28+
}
29+
30+
return this.parent.get(x)!;
31+
}
32+
33+
union(x: number, y: number): void {
34+
const rootX = this.find(x);
35+
const rootY = this.find(y);
36+
37+
if (rootX === rootY) return;
38+
39+
const sizeX = this.size.get(rootX);
40+
const sizeY = this.size.get(rootY);
41+
if (sizeX < sizeY) {
42+
this.parent.set(rootX, rootY);
43+
this.size.set(rootY, sizeX + sizeY);
44+
} else {
45+
this.parent.set(rootY, rootX);
46+
this.size.set(rootX, sizeX + sizeY);
47+
}
48+
}
49+
50+
getMaxSize(): number {
51+
let max = 0;
52+
for (const size of this.size.values()) {
53+
max = Math.max(max, size);
54+
}
55+
return max;
56+
}
57+
}
58+
function longestConsecutive(nums: number[]): number {
59+
if (nums.length === 0) return 0;
60+
61+
const uniqueNums = Array.from(new Set(nums));
62+
const uf = new UnionFind(uniqueNums);
63+
64+
for (const num of uniqueNums) {
65+
if (uf.parent.has(num + 1)) {
66+
uf.union(num, num + 1);
67+
}
68+
}
69+
70+
return uf.getMaxSize();
71+
}

0 commit comments

Comments
 (0)