目录
1、并查集原理
并查集是一种树型的数据结构,用于处理一些不相交集合的合并及查询问题(即并、查)。
例如:我们可以用并查集来判断一个森林中有几棵树、某个节点是否属于某棵树。
例如起初我们有一群人:
表示有10个人,每个人的下标为该人的编号,里面的值都为-1,表示该队伍只有一人
一段时间后,大家开始拉帮结派,组合成了如下队伍:
队伍一组长的编号为0,队伍二组长编号为1,队伍三组长编号为2
另一种表示形式:
该图的意思:
- 数组的下标对应集合中元素的编号
- 数组中如果为负数,负号代表根,数字代表该集合中元素个数
- 数组中如果为非负数,代表该元素双亲在数组中的下标
拉帮结派中,队伍可能会被另一个队伍拉拢,如下:
通过该例子,相信我们对并查集已经有了初步的理解,并查集一般可以解决如下问题:
- 查找元素属于哪个集合
沿着数组表示树形关系往上一直找到根(也就是树中元素为负数的位置)
- 查看两个元素是否属于同一个集合
沿着数组表示的树形关系往上一直找到树的根,如果根相同表明在同一个集合,否则不在
- 将两个集合归并成一个集合
将两个集合中的元素合并(将另一个集合名称改成另一个集合的名称)
- 集合的个数
遍历数组,数组中元素为负数的个数即为集合的个数
2、并查集实现
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* Description:
* User:龙宝
* Date:2023-02-04
* Time:20:10
*/
public class UnionFindSet {
public int[] elem;
public UnionFindSet(int n) {
this.elem = new int[n];
//为什么初始化为-1,因为每个值最开始的队伍中,只有自己一个人,值的绝对值表示
//队伍中人的个数,所以初始化为-1
Arrays.fill(elem,-1);
}
/**
* 查找数据x的根节点
* @param x
* @return
*/
public int findRoot (int x) {
if(x<0) {
throw new IndexOutOfBoundsException("下标不合法");
}
while (elem[x] >= 0) {
x = elem[x];
}
return x;
}
/**
* 查询x1,x2是否是同一个集合
* @param x1
* @param x2
* @return
*/
public boolean isSamUnionFindSet(int x1,int x2) {
int index1 = findRoot(x1);
int index2 = findRoot(x2);
if(index1 == index2) {
return true;
}
return false;
}
/**
* 合并
* @param x1
* @param x2
*/
public void union(int x1,int x2) {
int index1 = findRoot(x1);
int index2 = findRoot(x2);
if(index1 == index2) {
return;
}
elem[index1] = elem[index1] + elem[index2];
elem[index2] = index1;
}
public int getCount() {
int count = 0;
for(int x : elem) {
if(x < 0) {
count++;
}
}
return count;
}
}
3、算法题——Java实现【精选】
交换字符串中的元素
public class Num {
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
if(pairs.size() == 0) {
return s;
}
//1. 将任意交换的结点对输入并查集
int n = s.length();
UnionFind uf = new UnionFind(n);
for(List<Integer> pair : pairs) {
uf.union(pair.get(0), pair.get(1));
}
//2. 构建映射关系
//char[] charArray = s.toCharArray();
// key:连通分量的代表元,value:同一个连通分量的字符集合(保存在一个优先队列中)
Map<Integer, PriorityQueue<Character>> map = new HashMap<>(n);
for(int i = 0; i < n; i++) {
int root = uf.find(i);
map.computeIfAbsent(root, key -> new PriorityQueue<>()).offer(s.charAt(i));
}
//3. 重组字符串
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++) {
int root = uf.find(i);
sb.append(map.get(root).poll());
}
return sb.toString();
}
private class UnionFind {
private int[] parent;
private int[] rank;
public UnionFind(int n) {
this.parent = new int[n];
this.rank = new int[n];
for(int i = 0; i < n; i++) {
this.parent[i] = i;
this.rank[i] = 1;
}
}
public void union(int x, int y) {
int rootX = find(x), rootY = find(y);
if(rootX != rootY) {
if(rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
}else if(rank[rootX] < rank[rootY]) {
// 此时以 rootY 为根结点的树的高度不变
parent[rootX] = rootY;
}else {
parent[rootY] = rootX;
// 此时以 rootX 为根结点的树的高度仅加了 1
rank[rootX]++;
}
}
}
public int find(int x) {
if(parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
}
}
最长连续序列——【字节面试题考过】
public class Num {
public int longestConsecutive(int[] nums) {
int ans = 0;
//用来筛选某个数的左右连续数是否存在
Map<Integer, Integer> map = new HashMap<>();
//将连续的数字组成一个个集合
UnionFind uf = new UnionFind(nums.length);
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i])) continue;
if(map.containsKey(nums[i] - 1)) {//往左判断
uf.union(i, map.get(nums[i] - 1));
}
if(map.containsKey(nums[i] + 1)) {//往右判断
uf.union(i, map.get(nums[i] + 1));
}
map.put(nums[i], i);//存储当前数
}
for(int i = 0; i < nums.length; i++) {//选出最长的数
if(uf.find(i) != i) continue;//不是根节点
ans = Math.max(ans, uf.rank[i]);
}
return ans;
}
class UnionFind{
int[] parent;
int[] rank;
public UnionFind(int n) {
this.parent = new int[n];
this.rank = new int[n];
for(int i = 0; i < n; i++) {
this.parent[i] = i;
this.rank[i] = 1;
}
}
public void union(int x, int y) {
int rootX = find(x), rootY = find(y);
if(rootX != rootY) {
if(rank[rootX] < rank[rootY]) {
int tmp = rootX;
rootX = rootY;
rootY = tmp;
}
parent[rootY] = rootX;
rank[rootX] += rank[rootY];
}
}
public int find(int x) {
if(parent[x] != x){
parent[x] = find(parent[x]);
}
return parent[x];
}
}
}
连通网络的操作次数
public class Num {
public int makeConnected(int n, int[][] connections) {
//网线数量太少的情况 n是电脑数
if(connections.length < n - 1) return -1;
UnionFind uf = new UnionFind(n);
for(int[] connection : connections) {
uf.union(connection[0], connection[1]);
}
//只需要操作连通数量-1次即可
return uf.getCount() - 1;
}
class UnionFind{
int count;
int[] parent;
int[] rank;
public UnionFind(int n) {
this.count = n;
this.parent = new int[n];
this.rank = new int[n];
for(int i = 0; i < n; i++) {
this.parent[i] = i;
this.rank[i] = 1;
}
}
public int getCount() {
return count;
}
public void union(int x, int y) {
int rootX = find(x), rootY = find(y);
if(rootX != rootY) {
if(rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
}else if(rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
}else {
parent[rootY] = rootX;
rank[rootX]++;
}
count--;
}
}
public int find(int x) {
return parent[x] == x ? x : find(parent[x]);
}
}
}
最大岛屿数量
//三种解法
public class Num {
class UnionFind{
int count;
int[] parent;
int[] rank;
public UnionFind(char[][] grid) {
count = 0;
int m = grid.length;//行数
int n = grid[0].length;//列数
parent = new int[m * n];
rank = new int[m * n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1') {
parent[i * n + j] = i * n + j;//规律
count++;
}
rank[i * n + j] = 0;
}
}
}
public int find(int i) {
if(parent[i] != i) parent[i] = find(parent[i]);
return parent[i];
}
public void union(int x, int y) {
int rootX = find(x), rootY = find(y);
if(rootX != rootY) {
if(rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
}else if(rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
}else {
parent[rootY] = rootX;//相等的情况
rank[rootX] += 1;
}
count--;//维护数量
}
}
public int getCount() {
return count;
}
}
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int nr = grid.length;
int nc = grid[0].length;
int num_islands = 0;
UnionFind uf = new UnionFind(grid);
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
grid[r][c] = '0';
if (r - 1 >= 0 && grid[r-1][c] == '1') {
uf.union(r * nc + c, (r-1) * nc + c);
}
if (r + 1 < nr && grid[r+1][c] == '1') {
uf.union(r * nc + c, (r+1) * nc + c);
}
if (c - 1 >= 0 && grid[r][c-1] == '1') {
uf.union(r * nc + c, r * nc + c - 1);
}
if (c + 1 < nc && grid[r][c+1] == '1') {
uf.union(r * nc + c, r * nc + c + 1);
}
}
}
}
return uf.getCount();
}
//dfs —— 重点掌握
public int numIslands1(char[][] grid) {
int count = 0;
for(int i = 0; i < grid.length; i++) {//行数
for(int j = 0; j < grid[0].length; j++) {//列数
if(grid[i][j] == '1') {//满足条件就继续递归
dfs(grid, i, j);
count++;
}
}
}
return count;
}
private void dfs(char[][] grid, int i, int j) {
//终止条件
if(i < 0 || j < 0 || i >= grid.length ||
j >= grid[0].length || grid[i][j] == '0') return;
grid[i][j] = '0';
//分别向上下左右递归
dfs(grid, i + 1, j);
dfs(grid, i, j + 1);
dfs(grid, i - 1, j);
dfs(grid, i, j - 1);
}
//bfs
public int numIslands2(char[][] grid) {
int count = 0;
for(int i = 0; i < grid.length; i++) {
for(int j =0; j < grid[0].length; j++) {
if(grid[i][j] == '1') {
bfs(grid, i, j);
count++;
}
}
}
return count;
}
private void bfs(char[][] grid, int i, int j) {
Queue<int[]> list = new LinkedList<>();
list.add(new int[] {i, j});
while(!list.isEmpty()) {
int[] cur = list.remove();
i = cur[0]; j = cur[1];
if(0 <= i && i < grid.length && 0 <= j &&
j < grid[0].length && grid[i][j] == '1') {
grid[i][j] = '0';
list.add(new int[] {i + 1, j});
list.add(new int[] {i - 1, j});
list.add(new int[] {i, j + 1});
list.add(new int[] {i, j - 1});
}
}
}
}
省份数量
public class Num547 {
public int findCircleNum(int[][] isConnected) {
int provinces = isConnected.length;
int[] parent = new int[provinces];
//开辟一个parent数组 储存 某个节点的父节点
for(int i =0; i < provinces;i++){
parent[i] = i;
}
for(int i = 0; i < provinces; i++){
for(int j = i + 1; j < provinces; j++){
//两个节点只要是连通的就合并
if(isConnected[i][j] == 1){
union(parent, i, j);
}
}
}
int numProvinces = 0;
//扫描parent数组 如果当前节点对应根节点 就是一个省份
for(int i = 0; i < provinces; i++){
if(parent[i] == i){
numProvinces++;
}
}
return numProvinces;
}
//支持路径压缩的查找函数
public int find(int[] parent, int index){
//父节点不是自己
if(parent[index] != index){
//递归调用查找函数 并把当前结果储存在当前节点父节点数组中
parent[index] = find(parent, parent[index]);
}
//当父节点是本身时
return parent[index];
}
//合并函数
public void union(int[] parent, int index1, int index2){
parent[find(parent , index1)] = find(parent, index2);
}
//dfs
public int findCircleNum1(int[][] isConnected) {
int provinces = isConnected.length;
boolean[] visited = new boolean[provinces];
int numProvinces = 0;
for(int i = 0; i < provinces; i++) {
//如果该城市未被访问过,则从该城市开始深度优先搜索
if(!visited[i]) {
dfs(isConnected, visited, provinces, i);
numProvinces++;
}
}
return numProvinces;
}
private void dfs(int[][] isConnected, boolean[] visited, int provinces, int i) {
for(int j = 0; j < provinces; j++) {
//j时与i相连的邻居节点,相连且未被访问到
if(isConnected[i][j] == 1 && !visited[j]) {
visited[j] = true;
//继续做深度优先搜索
dfs(isConnected, visited, provinces, j);
}
}
}
}
冗余连接
public class Num {
public int[] findRedundantConnection(int[][] edges) {
int n = edges.length;
int[] parent = new int[n + 1];
for(int i = 1; i <= n; i++) {
parent[i] = i;
}
for(int i = 0; i < n; i++) {
int[] edge = edges[i];
int node1 =edge[0], node2 = edge[1];
//说明两个顶点不连通,当前边不会导致环出现
if(find(parent, node1) != find(parent, node2)) {
union(parent, node1, node2);
}else {//已经连通成环 返回该边即可
return edge;
}
}//这种情况表示没有
return new int[0];
}
public void union(int[] parent, int x, int y) {
parent[find(parent, x)] = find(parent, y);
}
public int find(int[] parent, int x) {
if(parent[x] != x) {
parent[x] = find(parent, parent[x]);
}
return parent[x];
}
}
冗余连接2
public class Num {
public int[] findRedundantDirectedConnection(int[][] edges) {
int n = edges.length;
UnionFind uf = new UnionFind(n + 1);
int[] parent = new int[n + 1];
for (int i = 1; i <= n; ++i) {
parent[i] = i;
}
int conflict = -1;
int cycle = -1;
for (int i = 0; i < n; ++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[] parent;
public UnionFind(int n) {
parent = new int[n];
for(int i = 0; i < n; i++) {
parent[i] = i;
}
}
public void union(int x, int y) {
parent[find(x)] = find(y);
}
public int find(int x) {
if(parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
}
情侣牵手【困难】
public class Num {
//如果一对情侣恰好坐在了一起,并且坐在了成组的座位上,
//其中一个下标一定是偶数,另一个一定是奇数,并且偶数的值 + 1 = 奇数的值。
//例如编号数对 [2, 3]、[9, 8],
//这些数对的特点是除以 2(下取整)得到的数相等。
public int minSwapsCouples(int[] row) {
int len = row.length;
int N = len >> 1;
UnionFind uf = new UnionFind(N);
for(int i = 0; i < len; i += 2) {
uf.union(row[i] >> 1, row[i + 1] >> 1);
}
return N - uf.getCount();
}
private class UnionFind {
private int[] parent;
private int count;
public int getCount() {
return count;
}
public UnionFind(int n) {
this.count = n;
this.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) {
int rootX = find(x), rootY = find(y);
if(rootX == rootY) return;
parent[rootX] = rootY;
count--;
}
}
}
移除最多的同行或同列石头
public class Num {
public int removeStones(int[][] stones) {
int sum = stones.length;
UnionFind uf = new UnionFind(sum);
for(int i = 0; i < sum; i++) {
//j 是 i 下一个石头
for(int j = i + 1; j < sum; j++) {
int x1 = stones[i][0], y1 = stones[i][1];
int x2 = stones[j][0], y2 = stones[j][1];
if(x1 == x2 || y1 == y2) {//处于同行或同列
uf.union(i, j);//粉碎石头
}
}
}
return sum - uf.getCount();
}
class UnionFind{
int count;
int[] parent;
int[] rank;
public UnionFind(int n) {
this.count = n;
this.parent = new int[n];
this.rank = new int[n];
for(int i = 0; i < n; i++) {
this.parent[i] = i;
this.rank[i] = 1;
}
}
public int getCount() {
return count;
}
public void union(int x, int y) {
int rootX = find(x), rootY = find(y);
if(rootX != rootY) {
if(rank[rootX] < rank[rootY]) {
int tmp = rootX;
rootX = rootY;
rootY = tmp;
}
parent[rootY] = rootX;
rank[rootX] += rank[rootY];
count--;
}
}
public int find(int x) {
return parent[x] == x ? x : find(parent[x]);
}
}
}
等式方程的可满足性
public class Num {
public boolean equationsPossible(String[] equations) {
int[] parent = new int[26];
for(int i = 0; i < 26; i++) {
parent[i] = i;
}
for(String str : equations) {
if(str.charAt(1) == '=') {
int x = str.charAt(0) - 'a';
int y = str.charAt(3) - 'a';
union(parent, x, y);
}
}
for(String str : equations) {
if(str.charAt(1) == '!') {
int x = str.charAt(0) - 'a';
int y = str.charAt(3) - 'a';
//说明连过了
if(find(parent, x) == find(parent, y)) {
return false;
}
}
}
return true;
}
public void union(int[] parent, int x, int y) {
parent[find(parent, x)] = find(parent, y);
}
public int find(int[] parent, int x) {
while(parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
}
并查集解题对我们来说就是一个模板,找到规律后,就可以在笔试中快速写出来~
好啦,我们下期见啦!!!