n 对情侣坐在连续排列的 2n 个座位上,想要牵到对方的手。
人和座位由一个整数数组 row 表示,其中 row[i] 是坐在第 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
解释: 无需交换座位,所有的情侣都已经可以手牵手了。
解题:
class UnionFind {
constructor(length) {
this.parent = new Array(length).fill(0).map((v, j) => j);
this.rank = new Array(length).fill(1);
this.setCount = length;
}
findSet(index) {
if (this.parent[index] !== index) {
this.parent[index] = this.findSet(this.parent[index]);
}
return this.parent[index];
}
unite(indei, index2) {
let root1 = this.findSet(indei),
root2 = this.findSet(index2);
if (root1 !== root2) {
if (this.rank[root1] < this.rank[root2]) {
[root1, root2] = [root2, root1];
}
this.parent[root2] = root1;
this.rank[root1] += this.rank[root2];
this.setCount--;
}
}
getCount() {
return this.setCount;
}
}
var minSwapsCouples = function (row) {
const len=row.length
const N=len>>1
const uf=new UnionFind(N)
for (let i = 0; i < len; i+=2) {
let cur=row[i],nextId=row[i+1]>>1;
//根据id>>1相等即为情侣的情况,将cur与next不相等的标记
if(cur!==nextId){
uf.unite(row[i]>>1,row[i+1]>>1)
}
}
return N - uf.getCount()
};