Skip to content

Commit 472df4e

Browse files
author
lucifer
committed
fix: uf 模板修复
1 parent 7af8d45 commit 472df4e

File tree

2 files changed

+38
-22
lines changed

2 files changed

+38
-22
lines changed

‎src/codeTemplates/uf.js

+33-22
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ class UF:
3232
parent = {}
3333
cnt = 0
3434
def __init__(self, M):
35-
# 初始化 parent 和 cnt
35+
# 初始化 parent,size 和 cnt
36+
for i in range(M):
37+
self.parent[i] = i
38+
self.cnt += 1
3639
3740
def find(self, x):
3841
while x != self.parent[x]:
@@ -77,14 +80,23 @@ class UF:
7780
size = {}
7881
cnt = 0
7982
def __init__(self, M):
80-
# 初始化 parent,size 和 cnt
81-
83+
# 初始化 parent,size 和 cnt
84+
for i in range(M):
85+
self.parent[i] = i
86+
self.size[i] = 1
87+
self.cnt += 1
8288
def find(self, x):
83-
while x != self.parent[x]:
84-
x = self.parent[x]
85-
# 路径压缩
86-
self.parent[x] = self.parent[self.parent[x]];
87-
return x
89+
# 根节点
90+
r = x
91+
while r != parent[r]:
92+
r = parent[r]
93+
k = x
94+
while k != r:
95+
# 暂存parent[k]的父节点
96+
j = parent[k]
97+
parent[k] = r
98+
k = j
99+
return r
88100
def union(self, p, q):
89101
if self.connected(p, q): return
90102
# 小的树挂到大的树上, 使树尽量平衡
@@ -129,21 +141,20 @@ class UF:
129141
text: `
130142
class UF:
131143
parent = {}
132-
def __init__(self, equations):
133-
# 做一些初始化操作
134-
144+
size = {}
145+
cnt = 0
146+
def __init__(self, M):
147+
# 初始化 parent,size 和 cnt
148+
for i in range(M):
149+
self.parent[i] = i
150+
self.size[i] = 1
151+
self.cnt += 1
135152
def find(self, x):
136-
# 根节点
137-
r = x
138-
while r != parent[r]:
139-
r = parent[r]
140-
k = x
141-
while k != r:
142-
# 暂存parent[k]的父节点
143-
j = parent[k]
144-
parent[k] = r
145-
k = j
146-
return r
153+
while x != self.parent[x]:
154+
x = self.parent[x]
155+
# 路径压缩
156+
self.parent[x] = self.parent[self.parent[x]];
157+
return x
147158
def union(self, p, q):
148159
if self.connected(p, q): return
149160
self.parent[self.find(p)] = self.find(q)

‎src/roadmap/roadmap.jsx

+5
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,11 @@ const items = [
202202
text: "233. 数字 1 的个数",
203203
link: "https://leetcode-cn.com/problems/number-of-digit-one/",
204204
},
205+
{
206+
text: "357. 计算各个位数不同的数字个数",
207+
link:
208+
"https://leetcode-cn.com/problems/count-numbers-with-unique-digits/",
209+
},
205210
{
206211
text: "902. 最大为 N 的数字组合",
207212
link:

0 commit comments

Comments
 (0)