0. 题目
1. 并查集+ 哈希表
import collections
class Solution:
def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:
n = len(source)+1
f = [i for i in range(n)]
def getfather(x):
if x != f[x]:
f[x] = getfather(f[x])
return f[x]
def union(x,y):
fx = getfather(x)
fy = getfather(y)
if fx!=fy:
f[fy] =fx
for i in range(len(allowedSwaps)):
union(allowedSwaps[i][0],allowedSwaps[i][1])
## 获取根节点对应的连通块
dicta = collections.defaultdict(list)
for i in range(len(source)):
fi = getfather(i)
dicta[fi].append(i)
res = 0
# 计算每个连通块对应的source元素与target的差集
#每个连同块内的元素可相互交换
for key,val in dicta.items():
a = [source[i] for i in val]
b = Counter(target[i] for i in val) # 统计相同元素的个数
for c in a:
if b[c]>0:
b[c] -=1 # 每匹配到一个元素,去掉它
else:
res+=1 # 匹配不上,有差集,差异个数+1
return res
source 与target的差集 和 target 与source差集是一样的
res = 0
for key,val in dicta.items():
a = Counter(source[i] for i in val)
b = [target[i] for i in val]
for c in b:
if a[c]>0:
a[c] -=1
else:
res+=1
return res