当前位置:网站首页>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;
}
};
边栏推荐
- OSS简单上传图片
- MySQL数据库 ---MySQL表的增删改查(进阶)
- 明解C语言第六章习题
- [PyTorchVideo Tutorial 01] Quickly implement video action recognition
- Install MySQL tutorial under Linux
- Linux下最新版MySQL 8.0的下载与安装(详细步骤)
- MySQL mass production of data
- Day31 LeetCode
- Based on the face of the common expression recognition - model building, training and testing
- Frog jumping steps (recursive and non-recursive) ------- Xiaolele walks the steps
猜你喜欢
随机推荐
Frog jumping steps (recursive and non-recursive) ------- Xiaolele walks the steps
MySQL sub-database sub-table
我是一名阿里在职9年软件测试工程师,我的经历也许能帮到处于迷茫期的你
MySQL数据库主从配置
Recommendation system: evaluation index [offline evaluation index: RMSE (root mean square error), AUC, precision, recall, F1] [online evaluation: A/B test] [generally required response time <0.5s]
历史上的今天:Win10 七周年;微软和雅虎的搜索协议;微软发行 NT 4.0
Niuke.com - Huawei Question Bank (100~108)
“数字化重构系统,搞定 CEO 是第一步”
MySQL performance optimization (hardware, system configuration, table structure, SQL statements)
Database indexes: indexes are not a panacea
Zabbix部署与练习
Face-based Common Expression Recognition (2) - Data Acquisition and Arrangement
Common Expression Recognition Based on Face (1) - Basic Knowledge of Deep Learning
MySQL database master-slave configuration
推荐系统:评估指标【离线评估指标:RMSE(均方根误差)、AUC、准确率、召回率、F1】【在线评估:A/B测试】【一般要求响应时间<0.5s】
MySQL分库分表
vlookup函数匹配不出来的原因及解决方法
WPS怎么独立窗口显示?wps单独窗口显示怎么操作?
网络层协议------IP协议
WPS表格怎么自动1234排下去?wps表格怎么自动生成序号?