根号n时间求出一个数的所有约数,但是大于门槛值的都直接丢弃,然后并查集合并这些数
class DSU {
int[] parent;
public DSU(int N) {
parent = new int[N];
for(int i = 0; i < N; ++ i) parent[i] = i;
}
public int find(int x) {
if(parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
public void union(int x, int y) {
parent[find(x)] = find(y);
}
}
class Solution {
public List<Boolean> areConnected(int n, int threshold, int[][] queries) {
List<Boolean> res = new ArrayList<>();
DSU dsu = new DSU(n + 1);
for(int i = 1; i <= n; i ++) {
List<Integer> temp = fun(i, threshold);
for(int j = 0; j < temp.size(); j ++) {
dsu.union(temp.get(j), i);
}
}
for(int i = 0; i < queries.length; i ++) {
int a = queries[i][0], b = queries[i][1];
if(dsu.find(a) == dsu.find(b)) res.add(true);
else res.add(false);
}
return res;
}
public List<Integer> fun(int n, int threshold) {
List<Integer> res = new ArrayList<>();
for(int i = 1; i <= Math.sqrt(n); i ++) {
if(n % i == 0) {
if(i > threshold) res.add(i);
if(n != i * i) {
if((n / i) > threshold) res.add(n / i);
}
}
}
Collections.sort(res);
return res;
}
}
``
// 之前错误的思路是:还是求约数个数,丢掉大于门槛值的数,排序,返回一个升序数组
// 然后用经典的双指针模板,求出两序列的共同的数,又没大于门槛值的,有就直接true
// 但是我没有考虑两个数通过第3个数相连通的情况,所以还是得用并查集处理
// 之前错误得代码如下:
class Solution {
public List<Boolean> areConnected(int n, int threshold, int[][] queries) {
List<Boolean> res = new ArrayList<>();
for(int i = 0; i < queries.length; i ++) {
int a = queries[i][0], b = queries[i][1];
if(a == b && a > threshold) {
res.add(true);
continue;
}
List<Integer> res1 = fun(a, threshold);
List<Integer> res2 = fun(b, threshold);
res.add(fun1(res1, res2, threshold));
}
return res;
}
public List<Integer> fun(int n, int threshold) {
List<Integer> res = new ArrayList<>();
for(int i = 1; i <= Math.sqrt(n); i ++) {
if(n % i == 0) {
if(i > threshold) res.add(i);
if(n != i * i) {
if((n / i) > threshold) res.add(n / i);
}
}
}
Collections.sort(res);
return res;
}
public Boolean fun1(List<Integer> res1, List<Integer> res2, int threshold) {
int i = 0, j = 0;
while(i < res1.size() && j < res2.size()) {
if(res1.get(i) > res2.get(j)) j ++;
else if(res1.get(i) < res2.get(j)) i ++;
else {
if(res1.get(i) > threshold) return true;
i ++; j ++;
}
}
return false;
}
}
作者:cyz3209
链接:https://leetcode-cn.com/problems/graph-connectivity-with-threshold/solution/qiu-yue-shu-as-well-as-bing-cha-ji-by-cyz3209/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。