Day27力扣打卡

打卡记录

Day27力扣打卡_第1张图片


情侣牵手(并查集)

链接

class Solution:
    def minSwapsCouples(self, row: List[int]) -> int:
        def find(x: int) -> int:
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        n = len(row) >> 1
        p = list(range(n))
        for i in range(0, len(row), 2):
            a, b = row[i] >> 1, row[i + 1] >> 1
            p[find(a)] = find(b)
        return n - sum(i == find(i) for i in range(n))

你可能感兴趣的:(leetcode刷题打卡,leetcode,算法,python)