作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/largest-component-size-by-common-factor/description/

题目描述

Given a non-empty array of unique positive integers A, consider the following graph:

  • There are A.length nodes, labelled A[0] to A[A.length - 1];
  • There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1.
    Return the size of the largest connected component in the graph.

Example 1:

Input: [4,6,15,35]
Output: 4

Example 2:

Input: [20,50,9,63]
Output: 2

Example 3:

Input: [2,3,6,7,4,12,21,39]
Output: 8

Note:

  1. 1 <= A.length <= 20000
  2. 1 <= A[i] <= 100000

题目大意

如果两个数有公因子,就把他们链接到一起。问最大的一条链上面有多少个元素。

解题方法

并查集

虽然这个题是hard题目,但是如果想明白了,很简单。任何两个数之间有相同的因子,就连接到一起,换句话说,可以把每个数字和它的所有因子进行链接,最后统计哪个因子上面的数字最多即可。

所以使用的方法是并查集,但是并不是把数组里面的两个元素进行合并,而是把每个数字和它所有的因子进行union。最后统计的数字也是某个因子上面的链接的数字的个数,因为这就是一条链的意思。

Python语言的效率比较慢,需要在find()的时候,做一次路径压缩。

class Solution:
def largestComponentSize(self, A):
"""
:type A: List[int]
:rtype: int
"""
ma = max(A)
N = len(A)
m = list(range(ma + 1))
for a in A:
for k in range(2, int(math.sqrt(a)) + 1):
if a % k == 0:
self.u(m, a, k)
self.u(m, a, a // k)
count = collections.defaultdict(int)
for a in A:
count[self.f(m, a)] += 1
return max(count.values()) def f(self, m, a):
while m[a] != a:
m[a] = m[m[a]]
a = m[a]
return a def u(self, m, a, b):
if m[a] == m[b]: return
pa = self.f(m, a)
pb = self.f(m, b)
m[pa] = pb

但是,C++的并查集不需要太对的路径压缩。效率快就是好。C++代码如下:

class Solution {
public:
int largestComponentSize(vector<int>& A) {
int mn = *max_element(A.begin(), A.end());
m_ = vector<int>(mn + 1, -1);
for (int i = 0; i < mn; i++) {
m_[i] = i;
}
const int N = A.size();
for (int a : A) {
for (int i = 2; i <= sqrt(a); i++){
if (a % i == 0) {
u(a, i);
u(a, a / i);
}
}
}
unordered_map<int, int> count;
for (int a : A) {
count[f(a)] ++;
}
int res = 0;
for (auto c : count) {
res = max(res, c.second);
}
return res;
}
private:
vector<int> m_;
vector<int> rank;
int f(int a) {
if (m_[a] == a)
return a;
m_[a] = f(m_[a]);
return m_[a];
}
void u(int a, int b) {
int pa = f(a);
int pb = f(b);
if (pa != pb) {
m_[pa] = m_[pb];
}
}
};

日期

2018 年 12 月 15 日 —— 今天四六级

【LeetCode】952. Largest Component Size by Common Factor 解题报告(Python & C++)的更多相关文章

  1. 【leetcode】952. Largest Component Size by Common Factor(Union find)

    You are given an integer array of unique positive integers nums. Consider the following graph: There ...

  2. [Swift]LeetCode952. 按公因数计算最大组件大小 | Largest Component Size by Common Factor

    Given a non-empty array of unique positive integers A, consider the following graph: There are A.len ...

  3. 「LeetCode」0952-Largest Component Size by Common Factor(Go)

    分析 注意到要求的是最大的连通分量,那么我们可以先打素数表(唯一分解定理),然后对每个要求的数,将他们同分解出的质因子相连(维护一个并查集),然后求出最大的联通分量即可. 这里使用了筛法求素数.初始化 ...

  4. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  5. 【LeetCode】450. Delete Node in a BST 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 日期 题目地址:https://leetcode ...

  6. 【LeetCode】380. Insert Delete GetRandom O(1) 解题报告(Python)

    [LeetCode]380. Insert Delete GetRandom O(1) 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxu ...

  7. 【LeetCode】718. Maximum Length of Repeated Subarray 解题报告(Python)

    [LeetCode]718. Maximum Length of Repeated Subarray 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxu ...

  8. 【LeetCode】833. Find And Replace in String 解题报告(Python)

    [LeetCode]833. Find And Replace in String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu ...

  9. 【九度OJ】题目1439:Least Common Multiple 解题报告

    [九度OJ]题目1439:Least Common Multiple 解题报告 标签(空格分隔): 九度OJ 原题地址:http://ac.jobdu.com/problem.php?pid=1439 ...

随机推荐

  1. nginx 文件目录页面

    开启文件目录 server { listen 80; #设置自己静态目录的访问域名 server_name xxx.xxxx.com; #防止页面中文乱码一定要在utf-8前面加上gbk,顺序很重要 ...

  2. 苹果ios通过描述文件获取udid

    苹果ios通过描述文件获取udid 需要准备的东西 1,安装描述文件只支持https的回调地址,所以需要申请https域名 2,描述文件签名,不安装也可,只要能接受红色的字 步骤: 1,准备xml文件 ...

  3. 14-Reverse Integer

    思路: 先判定符号,整型范围[-2^32,2^32] 取余除10操作,依次进行,越界返回0 Reverse digits of an integer. Example1: x = 123, retur ...

  4. 关于Stream的使用

    引言 Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找.过滤和映射数据等操作.使用Stream API 对集合数据进行操作,就类似于使用 ...

  5. windows磁盘扩容

    要邻近的磁盘,才可以扩展.所以必须要先删除恢复分区. 删除恢复分区,参考如下: https://jingyan.baidu.com/article/574c5219598d5e6c8c9dc15e.h ...

  6. Hadoop 相关知识点(二)

    1.HDFS副本机制 Hadoopde 默认副本布局策略是: (1)在运行客户端的节点上放置第一个副本(如果客户端运行在集群之外,就随机选择一个节点,不过系统会避免选择那些存储太满或者太忙的节点): ...

  7. org.apache.hadoop.hive.ql.metadata.HiveException: Internal Error: cannot generate all output rows for a Partition解决

    自己在路径访问明细表开发时,写的sql如下 SELECT guid, sessionid, event['url'] as page, `timestamp` as ts, row_number() ...

  8. 商业爬虫学习笔记day1

    day1 一. HTTP 1.介绍: https://www.cnblogs.com/vamei/archive/2013/05/11/3069788.html http://blog.csdn.ne ...

  9. 使用WtmPlus低代码平台提高生产力

    低代码平台的概念很火爆,产品也是鱼龙混杂. 对于开发人员来说,在使用绝大部分低代码平台的时候都会遇到一个致命的问题:我在上面做的项目无法得到源码,完全黑盒.一旦我的需求平台满足不了,那就是无解.   ...

  10. Android消除Toast延迟显示

    Toast可以用来显示音量改变或者保存更新消息,如果用户一直点击,Toast会排队一个一个的,直到消息队列全部显示完,这样的效果显然是不好的,下面来看解决方法    Toast.makeText(ac ...