力扣947.移除最多的同行或同列石头python解法

题目中要求我们去看看是否有同行,同列,我们可以尝试遍历所有进行比较,再添加一个参数去计算,但是这个复杂度有点高,我们是否可以用另一种方法进行遍历比较?
我们可以尝试用并查集进行问题的解决,如何解决?我们分别比较所有,有相同的就连接起来,并且参数会加1(删去一个元素),那我们可以直接用代码:

class UnionFind:
    def __init__(self):
        """
        记录每个节点的父节点
        """
        self.father = {}
        self.count = 0
    def find(self, x):
        """
        查找根节点
        路径压缩
        """
        root = x

        while self.father[root] != None:
            root = self.father[root]

        # 路径压缩
        while x != root:
            original_father = self.father[x]
            self.father[x] = root
            x = original_father

        return root

    def merge(self, x, y):
        """
        合并两个节点
        """
        root_x, root_y = self.find(x), self.find(y)

        if root_x != root_y:
            self.father[root_x] = root_y
            self.count += 1

    def add(self, x):
        """
        添加新节点
        """
        if x not in self.father:
            self.father[x] = None

class Solution:
    def removeStones(self, stones: List[List[int]]) -> int:
        n = len(stones)
        x = UnionFind()
        for i in range(n):
            x.add(i)
        for i in range(n):
            for j in range(i+1, n):
                if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]:
                    x.merge(i, j)
        return x.count

并查集讲解如下:
https://blog.csdn.net/qq_51718832/article/details/112340746

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leosaf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值