leetcode 1722

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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值