LeetCode 1722.执行交换操作后的最小汉明距离:连通图

【LetMeFly】1722.执行交换操作后的最小汉明距离:连通图

力扣题目链接:https://leetcode.cn/problems/minimize-hamming-distance-after-swap-operations/

给你两个整数数组 sourcetarget ,长度都是 n 。还有一个数组 allowedSwaps ,其中每个 allowedSwaps[i] = [ai, bi] 表示你可以交换数组 source 中下标为 aibi下标从 0 开始 )的两个元素。注意,你可以按 任意 顺序 多次 交换一对特定下标指向的元素。

相同长度的两个数组 sourcetarget 间的 汉明距离 是元素不同的下标数量。形式上,其值等于满足 source[i] != target[i]下标从 0 开始 )的下标 i0 <= i <= n-1)的数量。

在对数组 source 执行 任意 数量的交换操作后,返回 sourcetarget 间的 最小汉明距离

示例 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

提示:

  • n == source.length == target.length
  • 1 <= n <= 105
  • 1 <= source[i], target[i] <= 105
  • 0 <= allowedSwaps.length <= 105
  • allowedSwaps[i].length == 2
  • 0 <= ai, bi <= n - 1
  • ai != bi

解题方法:连通图

allowedPairs可以随便交换,我们可以据此构建BFS一个连通子图,一个连通子图中的所有下标可以任意交换。

具体而言,如果 a l l o w e d S w a p s [ i ] = [ a i , b i ] allowedSwaps[i] = [a_i, b_i] allowedSwaps[i]=[ai,bi],则看成 a i a_i ai和 b i b_i bi之间有一条边。遍历一遍 a l l o w e d S w a p s allowedSwaps allowedSwaps数组则可得到 g r a p h graph graph(其中 g r a p h [ i ] graph[i] graph[i]为所有与节点 i i i直接连通的节点们)。

对于一批可以相互交换的元素(一个连通子图),如何得知他的最小汉明距离呢?两种方法

方法一:一个数组一个set

数组 a a a中存放这个连通子图(其中任意节点可以随意交换) s o u r c e source source中的所有元素,multiset b b b存放这个连通子图 t a r g e t target target中的所有元素。

遍历数组 a a a中的元素,如果在 b b b中则匹配并抹去,如果不在则汉明距离加一。

方法二:一个map

一个map存放这个连通子图中元素的diff。 s o u r c e source source中元素则累计记数加一, t a r g e t target target中元素则累计计数减一。

最终遍历map所有键值对,值的绝对值之和即为总汉明距离的二倍。

时空复杂度分析

  • 时间复杂度 O ( n + m ) O(n+m) O(n+m),其中 m = l e n ( a l l o w e d S w a p s ) m=len(allowedSwaps) m=len(allowedSwaps)
  • 空间复杂度 O ( n + m ) O(n+m) O(n+m)

AC代码

C++ - 方法一
cpp 复制代码
/*
 * @LastEditTime: 2026-04-21 23:07:46
 */
class Solution {
private:
    inline void put(int node, vector<int>& source, vector<int>& target, vector<bool>& visited, vector<int>& a, unordered_multiset<int>& b, queue<int>& q) {
        q.push(node);
        visited[node] = true;
        a.push_back(source[node]);
        b.insert(target[node]);
    }

    int trace(int from, vector<int>& source, vector<int>& target, vector<vector<int>>& graph, vector<bool>& visited) {
        int ans = 0;
        queue<int> q;
        vector<int> a;
        unordered_multiset<int> b;
        
        put(from, source, target, visited, a, b, q);
        while (q.size()) {
            int from = q.front();
            q.pop();
            for (int to : graph[from]) {
                if (!visited[to]) {
                    put(to, source, target, visited, a, b, q);
                }
            }
        }

        for (int t : a) {
            unordered_multiset<int>::iterator it = b.find(t);
            if (it == b.end()) {
                ans++;
            } else {
                b.erase(it);
            }
        }
        return ans;
    }
public:
    int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {
        int n = source.size();
        vector<vector<int>> graph(n);
        for (vector<int>& s : allowedSwaps) {
            graph[s[0]].push_back(s[1]);
            graph[s[1]].push_back(s[0]);
        }
        int ans = 0;
        vector<bool> visited(n);
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                ans += trace(i, source, target, graph, visited);
            }
        }
        return ans;
    }
};
C++ - 方法二
cpp 复制代码
/*
 * @LastEditTime: 2026-04-21 23:14:07
 */
class Solution {
private:
    inline void put(int node, vector<int>& source, vector<int>& target, vector<bool>& visited, unordered_map<int, int>& diff, queue<int>& q) {
        q.push(node);
        visited[node] = true;
        diff[source[node]]++;
        diff[target[node]]--;
    }

    int trace(int from, vector<int>& source, vector<int>& target, vector<vector<int>>& graph, vector<bool>& visited) {
        int ans = 0;
        queue<int> q;
        unordered_map<int, int> diff;
        
        put(from, source, target, visited, diff, q);
        while (q.size()) {
            int from = q.front();
            q.pop();
            for (int to : graph[from]) {
                if (!visited[to]) {
                    put(to, source, target, visited, diff, q);
                }
            }
        }

        for (auto [_, d] : diff) {
            ans += abs(d);
        }
        return ans;
    }
public:
    int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {
        int n = source.size();
        vector<vector<int>> graph(n);
        for (vector<int>& s : allowedSwaps) {
            graph[s[0]].push_back(s[1]);
            graph[s[1]].push_back(s[0]);
        }
        int ans = 0;
        vector<bool> visited(n);
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                ans += trace(i, source, target, graph, visited);
            }
        }
        return ans / 2;
    }
};

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源

相关推荐
不知名的老吴2 小时前
案例教学:最长递增子序列问题
数据结构·算法·动态规划
样例过了就是过了2 小时前
LeetCode热题100 杨辉三角
c++·算法·leetcode·动态规划
念越2 小时前
算法每日一题 Day05|双指针解决盛最多水的容器问题
算法·力扣
eggrall2 小时前
Leetcode 最大连续 1 的个数 III(medium)
算法·leetcode·职场和发展
啊我不会诶2 小时前
Educational Codeforces Round 120 (Rated for Div. 2) vp补题
c++·算法
贾斯汀玛尔斯2 小时前
每天学一个算法--图算法(Graph Algorithms)
数据结构·算法
埃伊蟹黄面2 小时前
C++ —— 智能指针
开发语言·c++·算法
董董灿是个攻城狮2 小时前
马斯克在用炸火箭的方式训练 AGI。。。
算法
Pentane.2 小时前
【力扣hot100】【Leetcode 54】螺旋矩阵|边界控制 算法笔记及打卡(19/100)
算法·leetcode·矩阵