当前位置:网站首页>leetcode:952. 按公因数计算最大组件大小【并查集】
leetcode:952. 按公因数计算最大组件大小【并查集】
2022-07-29 19:40:00 【白速龙王的回眸】

分析
一个数,它和它所有的因数都应该是一组
然后对所有数都这样分解
最后,对所有数,可以得到root
这个root就是对应的分组
ac code
class Solution:
def largestComponentSize(self, nums: List[int]) -> int:
n = len(nums)
parent = list(range(10 ** 5 + 10))
def find(index: int) -> int:
if parent[index] != index:
parent[index] = find(parent[index])
return parent[index]
def union(index1: int, index2: int):
# 后者作为爸爸
parent[find(index1)] = find(index2)
for num in nums:
upper_bound = int(sqrt(num))
# core code
for i in range(2, upper_bound + 1):
if num % i == 0:
union(num, i)
union(num, num // i)
ans = 1
cnt = [0] * (10 ** 5 + 10)
for num in nums:
root = find(num)
cnt[root] += 1
ans = max(ans, cnt[root])
return ans
总结
简单并查集应用
边栏推荐
- 小程序onlaunch和onload(小程序onunload)
- C#_OpenCV使用相机
- [Mathematical Foundation] Learning about concepts related to linear algebra
- 经验分享|编写简单易用的在线产品手册小妙招
- MySQL 中的反斜杠 \\,怎么能这么坑?
- 经验分享|编写简单易用的在线产品手册小妙招
- exdark数据集转yolo格式(仅供参考)
- "Additional price" can not exchange for safety, the death of Lexus LM, whose fault is it?
- 解决宝塔mysql 远程root 无法连接问题
- JS实现倒计时代码实例「建议收藏」
猜你喜欢
随机推荐
TDengine 助力西门子轻量级数字化解决方案
敏捷组织 | 企业克服数字化浪潮冲击的路径
Gesture password unlock WeChat applet project source code
并发编程学习笔记 之 常用并发容器的概念及使用方法
HbuilderX打包app,Hbuilder怎么打包app,H5打包成app,H5怎么打包成app「建议收藏」
C# CLI(公共语言基础结构)
[mathematical foundation] probability and mathematical statistics related concept learning
12437字,带你深入探究RPC通讯原理
C language advanced enumeration and joint
使用IDEA连接mysql
【AutoSAR 四 BSW概述】
FPGA设计8位异步、同步二进制计数器
【AutoSAR 十 IO架构】
Chrome - Plugin Recommendations
【体系结构 一 概述】
JS实现倒计时代码实例「建议收藏」
H265码流RTP封装方式详解
本科毕业六年,疫情期间备战一个月,四面阿里巴巴定级P7
第二增长曲线 | 企业创新突破停滞困境的驱动指南
LeetCode 1047 删除字符串中的所有相邻重复项








