目录
1.朋友圈
(力扣547)班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。
给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数。
示例 1:
- 输入:[[1,1,0], [1,1,0], [0,0,1]]
- 输出:2
解释:已知学生 0 和学生 1 互为朋友,他们在一个朋友圈。第2个学生自己在一个朋友圈。所以返回 2 。
示例 2:
- 输入:[[1,1,0], [1,1,1], [0,1,1]]
- 输出:1
解释:已知学生 0 和学生 1 互为朋友,学生 1 和学生 2 互为朋友,所以学生 0 和学生 2 也是朋友,所以他们三个在一个朋友圈,返回 1 。
题解:https://leetcode-cn.com/problems/friend-circles/solution/peng-you-quan-by-leetcode/
代码实现:
//并查集
public class Solution {
int find(int parent[], int i) {
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
void union(int parent[], int x, int y) {
int xset = find(parent, x);
int yset = find(parent, y);
if (xset != yset)
parent[xset] = yset;
}
public int findCircleNum(int[][] M) {
int[] parent = new int[M.length];
Arrays.fill(parent, -1);
for (int i = 0; i < M.length; i++) {
for (int j = 0; j < M.length; j++) {
if (M[i][j] == 1 && i != j) {
union(parent, i, j);
}
}
}
int count = 0;
for (int i = 0; i < parent.length; i++) {
if (parent[i] == -1)
count++;
}
return count;
}
}
2.冗余连接
(力扣684)在本问题中, 树指的是一个连通且无环的无向图。
输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。
返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。
示例 1:
- 输入: [[1,2], [1,3], [2,3]]
- 输出: [2,3]
解释: 给定的无向图为:
1
/ \
2 - 3
示例 2:
- 输入: [[1,2], [2,3], [3,4], [1,4], [1,5]]
- 输出: [1,4]
解释: 给定的无向图为:
5 - 1 - 2
| |
4 - 3
题解:https://leetcode-cn.com/problems/redundant-connection/solution/java-bing-cha-ji-by-luma730/
代码实现:
class Solution {
//缓存结果集
int[] result = new int[2];
public int[] findRedundantConnection(int[][] edges) {
int[] father = new int[edges.length + 1];
for (int i = 0; i < father.length; i++) {
father[i] = i;
}
for (int[] edge : edges) {
union(father, edge[0], edge[1]);
}
return result;
}
//路径压缩
public int findXFather(int[] father, int x) {
while (father[x]!=x){
father[x] = father[father[x]];
x = father[x];
}
return x;
}
//合并两个能连接上的点,father合为最后确定的father
public void union(int[] father, int x, int y) {
int xFather = findXFather(father, x);
int yFather = findXFather(father, y);
if (xFather != yFather) {
father[xFather]=yFather;
} else {
//在发现两个点的连接已经存在时,就更新缓存,题目要最后一个,遍历到最后一个就是结果
result[0] = x;
result[1] = y;
}
}
}
3.冗余连接II
(力扣685)在本问题中,有根树指满足以下条件的有向图。该树只有一个根节点,所有其他节点都是该根节点的后继。每一个节点只有一个父节点,除了根节点没有父节点。
输入一个有向图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
结果图是一个以边组成的二维数组。 每一个边 的元素是一对 [u, v],用以表示有向图中连接顶点 u 和顶点 v 的边,其中 u 是 v 的一个父节点。
返回一条能删除的边,使得剩下的图是有N个节点的有根树。若有多个答案,返回最后出现在给定二维数组的答案。
示例 1:
- 输入: [[1,2], [1,3], [2,3]]
- 输出: [2,3]
解释: 给定的有向图如下:
1
/ \
v v
2-->3
示例 2:
- 输入: [[1,2], [2,3], [3,4], [4,1], [1,5]]
- 输出: [4,1]
解释: 给定的有向图如下:
5 <- 1 -> 2
^ |
| v
4 <- 3
代码实现:
class Solution {
public int[] findRedundantDirectedConnection(int[][] edges) {
int nodesCount = edges.length;
UnionFind uf = new UnionFind(nodesCount + 1);
int[] parent = new int[nodesCount + 1];
for (int i = 1; i <= nodesCount; ++i) {
parent[i] = i;
}
int conflict = -1;
int cycle = -1;
for (int i = 0; i < nodesCount; ++i) {
int[] edge = edges[i];
int node1 = edge[0], node2 = edge[1];
if (parent[node2] != node2) {
conflict = i;
} else {
parent[node2] = node1;
if (uf.find(node1) == uf.find(node2)) {
cycle = i;
} else {
uf.union(node1, node2);
}
}
}
if (conflict < 0) {
int[] redundant = {edges[cycle][0], edges[cycle][1]};
return redundant;
} else {
int[] conflictEdge = edges[conflict];
if (cycle >= 0) {
int[] redundant = {parent[conflictEdge[1]], conflictEdge[1]};
return redundant;
} else {
int[] redundant = {conflictEdge[0], conflictEdge[1]};
return redundant;
}
}
}
}
class UnionFind {
int[] ancestor;
public UnionFind(int n) {
ancestor = new int[n];
for (int i = 0; i < n; ++i) {
ancestor[i] = i;
}
}
public void union(int index1, int index2) {
ancestor[find(index1)] = find(index2);
}
public int find(int index) {
if (ancestor[index] != index) {
ancestor[index] = find(ancestor[index]);
}
return ancestor[index];
}
}
4.句子相似性II
(力扣737)给定两个句子 words1, words2 (每个用字符串数组表示),和一个相似单词对的列表 pairs ,判断是否两个句子是相似的。
例如,当相似单词对是 pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]的时候,words1 = ["great", "acting", "skills"] 和 words2 = ["fine", "drama", "talent"] 是相似的。
注意相似关系是 具有 传递性的。例如,如果 "great" 和 "fine" 是相似的,"fine" 和 "good" 是相似的,则 "great" 和 "good" 是相似的。
而且,相似关系是具有对称性的。例如,"great" 和 "fine" 是相似的相当于 "fine" 和 "great" 是相似的。
并且,一个单词总是与其自身相似。例如,句子 words1 = ["great"], words2 = ["great"], pairs = [] 是相似的,尽管没有输入特定的相似单词对。
最后,句子只会在具有相同单词个数的前提下才会相似。所以一个句子 words1 = ["great"] 永远不可能和句子 words2 = ["doubleplus","good"] 相似。
注:
- words1 and words2 的长度不会超过 1000。
- pairs 的长度不会超过 2000。
- 每个pairs[i] 的长度为 2。
- 每个 words[i] 和 pairs[i][j] 的长度范围为 [1, 20]。
题解:https://leetcode-cn.com/problems/sentence-similarity-ii/solution/sentence-similarity-ii-by-leetcode/
代码实现:
class Solution {
public boolean areSentencesSimilarTwo(String[] words1, String[] words2, String[][] pairs) {
if (words1.length != words2.length) return false;
Map<String, Integer> index = new HashMap();
int count = 0;
DSU dsu = new DSU(2 * pairs.length);
for (String[] pair: pairs) {
for (String p: pair) if (!index.containsKey(p)) {
index.put(p, count++);
}
dsu.union(index.get(pair[0]), index.get(pair[1]));
}
for (int i = 0; i < words1.length; ++i) {
String w1 = words1[i], w2 = words2[i];
if (w1.equals(w2)) continue;
if (!index.containsKey(w1) || !index.containsKey(w2) ||
dsu.find(index.get(w1)) != dsu.find(index.get(w2)))
return false;
}
return true;
}
}
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);
}
}
5.等式方程的可满足性
(力扣990)给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
示例 1:
- 输入:["a==b","b!=a"]
- 输出:false
解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。
示例 2:
- 输入:["b==a","a==b"]
- 输出:true
解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。
示例 3:
- 输入:["a==b","b==c","a==c"]
- 输出:true
示例 4:
- 输入:["a==b","b!=c","c==a"]
- 输出:false
示例 5:
- 输入:["c==c","b==d","x!=z"]
- 输出:true
提示:
- 1 <= equations.length <= 500
- equations[i].length == 4
- equations[i][0] 和 equations[i][3] 是小写字母
- equations[i][1] 要么是 '=',要么是 '!'
- equations[i][2] 是 '='
代码实现:
class Solution {
public boolean equationsPossible(String[] equations) {
int length = equations.length;
int[] parent = new int[26];
for (int i = 0; i < 26; i++) {
parent[i] = i;
}
for (String str : equations) {
if (str.charAt(1) == '=') {
int index1 = str.charAt(0) - 'a';
int index2 = str.charAt(3) - 'a';
union(parent, index1, index2);
}
}
for (String str : equations) {
if (str.charAt(1) == '!') {
int index1 = str.charAt(0) - 'a';
int index2 = str.charAt(3) - 'a';
if (find(parent, index1) == find(parent, index2)) {
return false;
}
}
}
return true;
}
public void union(int[] parent, int index1, int index2) {
parent[find(parent, index1)] = find(parent, index2);
}
public int find(int[] parent, int index) {
while (parent[index] != index) {
parent[index] = parent[parent[index]];
index = parent[index];
}
return index;
}
}
6.连通网络的操作次数
(力扣1319)用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。
网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。
给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。
示例 1:
- 输入:n = 4, connections = [[0,1],[0,2],[1,2]]
- 输出:1
解释:拔下计算机 1 和 2 之间的线缆,并将它插到计算机 1 和 3 上。
示例 2:
- 输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
- 输出:2
示例 3:
- 输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
- 输出:-1
解释:线缆数量不足。
示例 4:
- 输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
- 输出:0
提示:
- 1 <= n <= 10^5
- 1 <= connections.length <= min(n*(n-1)/2, 10^5)
- connections[i].length == 2
- 0 <= connections[i][0], connections[i][1] < n
- connections[i][0] != connections[i][1]
- 没有重复的连接。
- 两台计算机不会通过多条线缆连接。
代码实现:
class Solution {
int[] father;
int[] sz;
int num;
public int find(int p) {
if (p != father[p]) {
p = find(father[p]);
}
return p;
}
public void union(int p, int q) {
int i = find(p);
int j = find(q);
if (i == j) return;
num -= 1;
if (sz[i] < sz[j]) {
father[i] = j;
sz[j] += sz[i];
} else {
father[j] = i;
sz[i] += sz[j];
}
}
public void initUF(int n) {
father = new int[n];
sz = new int[n];
num = n;
for (int i = 0; i < n; i++) {
father[i] = i;
sz[i] = 1;
}
}
public int makeConnected(int n, int[][] connections) {
initUF(n);
// 多余的线缆数量
int cnt = 0;
for (int[] c : connections) {
int f = c[0], t = c[1];
// 两个点已经连通,不需要这个线缆
if (find(f) == find(t)) {
cnt += 1;
continue;
}
union(f, t);
}
// 所需要的线缆数量
int cnt2 = num - 1;
if (cnt < cnt2) {
return -1;
}
return cnt2;
}
}
7.按公因数计算最大组件的大小
(力扣952)给定一个由不同正整数的组成的非空数组 A,考虑下面的图:
- 有 A.length 个节点,按从 A[0] 到 A[A.length - 1] 标记;
- 只有当 A[i] 和 A[j] 共用一个大于 1 的公因数时,A[i] 和 A[j] 之间才有一条边。
返回图中最大连通组件的大小。
示例 1:
- 输入:[4,6,15,35]
- 输出:4
示例 2:
- 输入:[20,50,9,63]
- 输出:2
示例 3:
- 输入:[2,3,6,7,4,12,21,39]
- 输出:8
代码实现:
class Solution {
public int largestComponentSize(int[] A) {
int N = A.length;
// factored[i] = a list of unique prime factors of A[i]
ArrayList<Integer>[] factored = new ArrayList[N];
for (int i = 0; i < N; ++i) {
factored[i] = new ArrayList<Integer>();
int d = 2, x = A[i];
while (d * d <= x) {
if (x % d == 0) {
while (x % d == 0)
x /= d;
factored[i].add(d);
}
d++;
}
if (x > 1 || factored[i].isEmpty())
factored[i].add(x);
}
// primesL : a list of all primes that occur in factored
Set<Integer> primes = new HashSet();
for (List<Integer> facs: factored)
for (int x: facs)
primes.add(x);
int[] primesL = new int[primes.size()];
int t = 0;
for (int x: primes)
primesL[t++] = x;
// primeToIndex.get(v) == i iff primes[i] = v
Map<Integer, Integer> primeToIndex = new HashMap();
for (int i = 0; i < primesL.length; ++i)
primeToIndex.put(primesL[i], i);
DSU dsu = new DSU(primesL.length);
for (List<Integer> facs: factored)
for (int x: facs)
dsu.union(primeToIndex.get(facs.get(0)), primeToIndex.get(x));
int[] count = new int[primesL.length];
for (List<Integer> facs: factored)
count[dsu.find(primeToIndex.get(facs.get(0)))]++;
int ans = 0;
for (int x: count)
if (x > ans)
ans = x;
return ans;
}
}
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);
}
}