阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给你两个长度为 n 的整数数组 source 和 target,以及一个表示可交换下标的二维数组 allowedSwaps。 你可以按任意顺序、任意次数交换 allowedSwaps 中指定的下标对。 汉明距离定义为两个数组中元素不同的下标数量。 要求:在对 source 执行任意数量的允许交换后,返回它与 target 之间的最小汉明距离。
示例: 输入:
source = [1,2,3,4]target = [2,1,4,5]allowedSwaps = [[0,1],[2,3]] 输出:1 解释:[2,1,3,4][2,1,4,3][2,1,4,5] 只有下标 3 处不同,汉明距离为 1。source 中这些位置的元素可以任意排列。target 中每个位置的元素,优先与同一连通分量内 source 中存在的元素匹配。allowedSwaps 构建所有下标之间的连通分量。source 数组,统计每个连通分量内,各元素出现的次数。target 数组,对于每个位置,在其对应的连通分量中查找是否存在该元素的剩余次数: package lc1722;
import java.util.HashMap;
import java.util.Map;
class Solution {
public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {
int n = source.length;
UnionFind uf = new UnionFind(n);
for (int[] swap : allowedSwaps) {
uf.union(swap[0], swap[1]);
}
Map<Integer, Map<Integer, Integer>> groupCount = new HashMap<>();
for (int i = 0; i < n; i++) {
int root = uf.find(i);
groupCount.computeIfAbsent(root, k -> new HashMap<>())
.put(source[i], groupCount.get(root).getOrDefault(source[i], 0) + 1);
}
int res = 0;
for (int i = 0; i < n; i++) {
int root = uf.find(i);
Map<Integer, Integer> count = groupCount.get(root);
if (count.containsKey(target[i]) && count.get(target[i]) > 0) {
count.put(target[i], count.get(target[i]) - 1);
} else {
res++;
}
}
return res;
}
static class UnionFind {
int[] parent;
public UnionFind(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) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
parent[fy] = fx;
}
}
}
}Map<Integer, Map<Integer, Integer>> 统计每个连通分量内的元素频率,空间利用率高。target 数组上单次遍历,直接匹配并消耗 source 中元素的计数,避免了二次遍历。时间复杂度:
target 数组:空间复杂度:
target 进行贪心匹配即可。