Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3f2a3d6

Browse files
committed
added longest-consecutive-sequence
1 parent b5e085a commit 3f2a3d6

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎data_structure/union_find.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,38 @@ class Solution:
6363
return [[email2name[s[0]]] + sorted(s) for s in result.values()]
6464
```
6565

66+
### [longest-consecutive-sequence](https://leetcode-cn.com/problems/longest-consecutive-sequence/)
6667

68+
```Python
69+
class Solution:
70+
def longestConsecutive(self, nums: List[int]) -> int:
71+
72+
parent = {num: num for num in nums}
73+
length = {num: 1 for num in nums}
74+
75+
def find(x):
76+
if parent[parent[x]] != parent[x]:
77+
parent[x] = find(parent[x])
78+
return parent[x]
79+
80+
def union(x, y):
81+
px, py = find(x), find(y)
82+
if px != py:
83+
parent[px] = py
84+
length[py] += length[px]
85+
return
86+
87+
max_length = 0
88+
for num in nums:
89+
if num + 1 in parent:
90+
union(num + 1, num)
91+
if num - 1 in parent:
92+
union(num - 1, num)
93+
94+
max_length = max(max_length, length[parent[num]])
95+
96+
return max_length
97+
```
6798

6899
### Kruskal's algorithm
69100

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /