当前位置: 首页 > article >正文

Leetcode 3493. Properties Graph

  • Leetcode 3493. Properties Graph
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接:3493. Properties Graph

1. 解题思路

这一题的话是要考虑最终聚合的簇的个数,因此很明显就是一个并查集的典型题目。因此,我们只需要创建一个并查集,然后两两考察其各自的关联关系即可。

而关于并查集的相关内容,网上已经有很多了,我自己也有一篇拙作(经典算法:并查集(DSU)结构简介)来作备忘。所以这里就不过多展开了,有兴趣的读者可以自行了解一下相关的内容。

2. 代码实现

给出python代码实现如下:

class DSU:
    def __init__(self, N):
        self.root = [i for i in range(N)]
        
    def find(self, k):
        if self.root[k] != k:
            self.root[k] = self.find(self.root[k])
        return self.root[k]
    
    def union(self, a, b):
        x = self.find(a)
        y = self.find(b)
        if x != y:
            self.root[y] = x
        return

class Solution:
    def numberOfComponents(self, properties: List[List[int]], k: int) -> int:
        elems = [set(x) for x in properties]
        n = len(properties)
        dsu = DSU(n)
        for i in range(n-1):
            for j in range(i+1, n):
                intersect = len(elems[i] & elems[j])
                if intersect >= k:
                    dsu.union(i, j)
        clusters = [dsu.find(i) for i in range(n)]
        return len(set(clusters))

提交代码评测得到:耗时206ms,占用内存18.7MB。


http://www.kler.cn/a/599934.html

相关文章:

  • Vue 表单输入绑定,双向绑定
  • 蓝桥杯2022年第十三届决赛真题-最大数字
  • STC89C52单片机学习——第35节: [16-1] AD/DA
  • Unocss 和 Tailwindcss 对比
  • Linux | make和Makefile命令详细篇
  • 性能优化:python中的状态机
  • 在fedora41中使用最新版本firefox和腾讯翻译插件让英文网页显示中文翻译
  • 数据库设计-笔记3
  • 项目总结:GetX + Kotlin 协程实现跨端音乐播放实时同步
  • 正则表达式与表单验证详解
  • 精神分裂症分类的图神经网络和多模态DTI特征
  • curl使用报错error LNK2001: 无法解析的外部符号 __imp__CertCloseStore@8
  • 卷积神经网络的传播及参数用法
  • MLP 多层感知机+权重衰减+L1L2范数+激活函数
  • 【Linux xargs命令深度解析与实践指南】
  • prometheus + alertmanager + grafana 监控拓扑图
  • the AI Workflow Types note at 2025
  • 【 <二> 丹方改良:Spring 时代的 JavaWeb】之 Spring MVC 的核心组件:DispatcherServlet 的工作原理
  • npm报错‘proxy‘ config is set properxy. See: ‘npm help config‘
  • 文档处理控件Aspose.Words 教程:.NET版中增强的 AI 文档摘要功能