【数据结构-并查集】力扣1722. 执行交换操作后的最小汉明距离
给你两个整数数组 source 和 target ,长度都是 n 。还有一个数组 allowedSwaps ,其中每个 allowedSwaps[i] = [ai, bi] 表示你可以交换数组 source 中下标为 ai 和 bi(下标从 0 开始)的两个元素。注意,你可以按 任意 顺序 多次 交换一对特定下标指向的元素。
相同长度的两个数组 source 和 target 间的 汉明距离 是元素不同的下标数量。形式上,其值等于满足 source[i] != target[i] (下标从 0 开始)的下标 i(0 <= i <= n-1)的数量。
在对数组 source 执行 任意 数量的交换操作后,返回 source 和 target 间的 最小汉明距离 。
示例 1:
输入:source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
输出:1
解释:source 可以按下述方式转换:
- 交换下标 0 和 1 指向的元素:source = [2,1,3,4]
- 交换下标 2 和 3 指向的元素:source = [2,1,4,3]
source 和 target 间的汉明距离是 1 ,二者有 1 处元素不同,在下标 3 。
示例 2:
输入:source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []
输出:2
解释:不能对 source 执行交换操作。
source 和 target 间的汉明距离是 2 ,二者有 2 处元素不同,在下标 1 和下标 2 。
示例 3:
输入:source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]
输出:0
并查集
class UnionFind{
private:
vector<int> parent;
public:
UnionFind(int n){
parent.resize(n);
for(int i = 0; i < n; i++){
parent[i] = i;
}
}
int find(int index){
if(parent[index] == index){
return index;
}
parent[index] = find(parent[index]);
return parent[index];
}
void unite(int index1, int index2){
int root1 = find(index1);
int root2 = find(index2);
parent[root2] = root1;
}
};
class Solution {
public:
int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {
int n = source.size();
UnionFind uf(n);
for(auto& c : allowedSwaps){
uf.unite(c[0], c[1]);
}
unordered_map<int, vector<int>> groups; // 存储每个集合的元素
for (int i = 0; i < n; i++) {
groups[uf.find(i)].push_back(i);
}
int cnt = 0;
for (auto& group : groups) {
unordered_map<int, int> sourceCount;
for (int idx : group.second) {
sourceCount[source[idx]]++;
}
// 计算组内无法匹配的元素数量
for (int idx : group.second) {
if (sourceCount[target[idx]] > 0) {
// 如果当前元素能匹配,则减少 sourceCount 中的数量
sourceCount[target[idx]]--;
} else {
// 否则计算汉明距离
cnt++;
}
}
}
return cnt;
}
};
首先根据allowedSwaps的元素来进行并查集合并,来合并对应序号的元素。将对应序号进行合并了以后,我们定义一个哈希表groups,键是集合的根节点,值是该集合下的所有元素。然后我们通过遍历i从0到n-1,来填充groups,这样接下来通过groups就可以知道那些索引是属于同一个集合。
接下来我们遍历groups,group.second代表同一个集合中的索引。我们定义哈希表sourceCount来记录该集合下source中元素数量。
我们接着就可以计算组内无法匹配的元素数量,我们遍历该集合group.second,即遍历该集合下的索引idx,只有当sourceCount[target[idx]]大于0的时候,我们可以通过调换顺序使得source[idx]和target[idx]匹配,当sourceCount[target[idx]]小于0的时候,说明source的该集合索引中已经没有元素可以用来匹配target[idx],这时候我们就增加汉明距离。