leetcode 765 情侣牵手问题,并查集+问题转换能力

分析:假设有 N对情侣,假设有 K 个集合(存在情侣的集合),(偶数,偶数+1)为一个元素最少的集合这种情况符合题意不需要交换。假设每个集合里面有 m1,m2, m3.......mk个元素,需要进行m1-1,m2-1, m3-1.......mk-1次交换,求和得到本题答案为N - K

class UnionSet:
    def __init__(self, n):
        self.father = list(range(n))
    def find(self, ind): #找寻元素的根节点
        if self.father[ind] == ind:
            return ind
        self.father[ind] = self.find(self.father[ind]) 
        return self.father[ind]
    def union(self, x, y): #将y并入x类
        root_x = self.find(x) #x位置元素,根节点为root_x编号元素
        root_y = self.find(y) #y位置元素,根节点为root_y编号元素
        if root_x != root_y:              
            self.father[root_y] = root_x #把root_y编号元素的父节点,替换为root_x
        return
    def isConnection(self, x, y):
        return self.find(x) == self.find(y)

class Solution:
    def minSwapsCouples(self, row: List[int]) -> int:
        n = len(row) // 2
        us = UnionSet(n)
        for i in range(0, len(row) , 2):
            left = row[i] // 2
            right = row[i+1] // 2

            if left != right:
                us.union(left, right)

        set_count = 0
        for i in range(n):
            if us.find(i) == i:
                set_count += 1

        return n - set_count

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值