当前位置:网站首页>365天挑战LeetCode1000题——Day 044 按公因数计算最大组件大小 并查集
365天挑战LeetCode1000题——Day 044 按公因数计算最大组件大小 并查集
2022-07-30 20:00:00 【ShowM3TheCode】
952. 按公因数计算最大组件大小

代码实现(部分看题解)
这题我想两两求公因数,但是不行,很奇怪,反而是答案看上去笨笨的枚举可以。
class DisjointSet {
private:
std::vector<int> parent;
std::vector<int> rank; // 秩
int maxSetNum;
public:
DisjointSet(int max_size) : parent(std::vector<int>(max_size)), rank(std::vector<int>(max_size, 1)), maxSetNum(1) {
for (int i = 0; i < max_size; ++i) parent[i] = i;
}
int find(int x) {
return x == parent[x] ? x : (parent[x] = find(parent[x]));
}
void _union(int x1, int x2) {
int f1 = find(x1);
int f2 = find(x2);
if (f1 == f2) return;
if (rank[f1] > rank[f2]) {
parent[f2] = f1;
rank[f1] += rank[f2];
maxSetNum = max(maxSetNum, rank[f1]);
}
else {
parent[f1] = f2;
rank[f2] += rank[f1];
maxSetNum = max(maxSetNum, rank[f2]);
}
}
bool is_same(int e1, int e2) {
return find(e1) == find(e2);
}
int getHighestRank() {
return maxSetNum;
}
};
class Solution {
public:
int largestComponentSize(vector<int>& nums) {
int n = *max_element(nums.begin(), nums.end());
DisjointSet ds(n + 1);
for (int num : nums) {
for (int j = 2; j * j <= num; j++) {
if (num % j == 0) {
ds._union(num, num / j);
ds._union(num, j);
}
}
}
vector<int> counts(n + 1);
int root = 0, ans = 0;
for (int num : nums) {
root = ds.find(num);
counts[root]++;
ans = max(ans, counts[root]);
}
return ans;
}
};
边栏推荐
- MySQL六脉神剑,SQL通关大总结
- Typora设置标题自动标号
- 网络层协议------IP协议
- MySQL性能优化(硬件,系统配置,表结构,SQL语句)
- ceph的部署练习
- 明解C语言第五章习题
- coming!Dongfang Selection brings goods to the live broadcast of Longjiang agricultural products
- jOOQ是如何设计事务API(详细指南)
- 从离线到实时对客,湖仓一体释放全量数据价值
- Linux download and install mysql5.7 version tutorial the most complete and detailed explanation
猜你喜欢

MySQL数据库 ---MySQL表的增删改查(进阶)

Face-based Common Expression Recognition (2) - Data Acquisition and Arrangement

18.客户端会话技术Cookie

MySQL分组后取最大一条数据【最优解】

并发与并行的区别

网络层协议------IP协议

推荐系统-排序层:排序层架构【用户、物品特征处理步骤】

ELK日志分析系统

Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
Typora设置标题自动标号
随机推荐
【PM专用】快速统计团队还有谁没有登记上报信息,快速筛选出属于自己项目组的成员,未完成XXX工作事项的名单
vlookup函数匹配不出来的原因及解决方法
阿里面试这些微服务还不会?那还是别去了,基本等通知
The JDBC programming of the MySQL database
MySQL slow query optimization
Database Tuning - Database Tuning
【视频】极值理论EVT与R语言应用:GPD模型火灾损失分布分析
Is the iPhone really thirteen incense?The two generations of products are completely compared, perhaps the previous generation is more worth buying
[Node implements data encryption]
Download and installation of the latest version of MySQL 8.0 under Linux (detailed steps)
ELK log analysis system
18.客户端会话技术Cookie
Download Win11 how to change the default path?Download Win11 change the default path method
musicApp 的.eslintrc.js
【Node实现数据加密】
网络层协议------IP协议
Linux download and install mysql5.7 version tutorial the most complete and detailed explanation
从离线到实时对客,湖仓一体释放全量数据价值
HarmonyOS笔记-----------(三)
HCIP --- 企业网的三层架构