765. 情侣牵手(并查集)

765. 情侣牵手

n 对情侣坐在连续排列的 2n 个座位上,想要牵到对方的手。

人和座位由一个整数数组 row 表示,其中 row[i] 是坐在第 个座位上的人的 ID。情侣们按顺序编号,第一对是 (0, 1),第二对是 (2, 3),以此类推,最后一对是 (2n-2, 2n-1)

返回 最少交换座位的次数,以便每对情侣可以并肩坐在一起。 每次交换可选择任意两人,让他们站起来交换座位。

 

示例 1:

输入: row = [0,2,1,3]
输出: 1
解释: 只需要交换row[1]和row[2]的位置即可。

示例 2:

输入: row = [3,2,0,1]
输出: 0
解释: 无需交换座位,所有的情侣都已经可以手牵手了。

 

提示:

  • 2n == row.length
  • 2 <= n <= 30
  • n 是偶数
  • 0 <= row[i] < 2n
  • row 中所有元素均无重复
复制代码
 1 class Solution {
 2 public:
 3     vector<int> parent;
 4     int numOfGroup;
 5     void initUnionFind(int n) {
 6         parent.resize(n);
 7         numOfGroup = n;
 8         for (int i = 0; i < n; i++) {
 9             parent[i] = i;
10         }
11     }
12     int findRoot(int x) {
13         int root = x;
14         while (root != parent[root]) {
15             root = parent[root];
16         }
17         while (x != root) {
18             int next = parent[x];
19             parent[x] = root;
20             x = next;
21         }
22         return root;
23     }
24     bool isConnected(int x, int y) {
25         return (findRoot(x) == findRoot(y));
26     }
27     void unify(int x, int y) {
28         if (isConnected(x, y)) {
29             return;
30         }
31         int xRoot = findRoot(x);
32         int yRoot = findRoot(y);
33         if (xRoot < yRoot) {
34             parent[xRoot] = yRoot;
35         } else {
36             parent[yRoot] = xRoot;
37         }
38         numOfGroup--;
39         return;
40     }
41     int minSwapsCouples(vector<int>& row) {
42         int length = row.size(); // 座位或者人的个数
43         int n = length / 2; // n对情侣
44         initUnionFind(n); // 初始化并查集
45         for (int i = 0; i < length; i+= 2) {
46             unify(row[i] / 2, row[i + 1] / 2);
47         }
48         // 结果为交换后的情侣对(组数) - 交换前的情侣对(组数)
49         return (n - numOfGroup);
50     }
51 };
复制代码
posted @   跳动的休止符  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示