N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.

The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1).

The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat.

Example 1:

Input: row = [0, 2, 1, 3]
Output: 1
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.

Example 2:

Input: row = [3, 2, 0, 1]
Output: 0
Explanation: All couples are already seated side by side. 

Note:

  1. len(row) is even and in the range of [4, 60].
  2. row is guaranteed to be a permutation of 0...len(row)-1.

有N个情侣和2N个座位,想让每一对情侣都能够牵手,也就是挨着坐。每次能交换任意两个人的座位,求最少需要换多少次座位。

解法1:cyclic swapping

解法2: Union Find

Java: 1

public int minSwapsCouples(int[] row) {
int res = 0, N = row.length; int[] ptn = new int[N];
int[] pos = new int[N]; for (int i = 0; i < N; i++) {
ptn[i] = (i % 2 == 0 ? i + 1 : i - 1);
pos[row[i]] = i;
} for (int i = 0; i < N; i++) {
for (int j = ptn[pos[ptn[row[i]]]]; i != j; j = ptn[pos[ptn[row[i]]]]) {
swap(row, i, j);
swap(pos, row[i], row[j]);
res++;
}
} return res;
} private void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}

Java: 2

class Solution {
private class UF {
private int[] parents;
public int count;
UF(int n) {
parents = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
}
count = n;
} private int find(int i) {
if (parents[i] == i) {
return i;
}
parents[i] = find(parents[i]);
return parents[i];
} public void union(int i, int j) {
int a = find(i);
int b = find(j);
if (a != b) {
parents[a] = b;
count--;
}
}
}
public int minSwapsCouples(int[] row) {
int N = row.length/ 2;
UF uf = new UF(N);
for (int i = 0; i < N; i++) {
int a = row[2*i];
int b = row[2*i + 1];
uf.union(a/2, b/2);
}
return N - uf.count;
}
} 

Python:

# Time:  O(n)
# Space: O(n) class Solution(object):
def minSwapsCouples(self, row):
"""
:type row: List[int]
:rtype: int
"""
N = len(row)//2
couples = [[] for _ in xrange(N)]
for seat, num in enumerate(row):
couples[num//2].append(seat//2)
adj = [[] for _ in xrange(N)]
for couch1, couch2 in couples:
adj[couch1].append(couch2)
adj[couch2].append(couch1) result = 0
for couch in xrange(N):
if not adj[couch]: continue
couch1, couch2 = couch, adj[couch].pop()
while couch2 != couch:
result += 1
adj[couch2].remove(couch1)
couch1, couch2 = couch2, adj[couch2].pop()
return result # also equals to N - (# of cycles)  

C++:

int minSwapsCouples(vector<int>& row) {
int res = 0, N = row.size(); vector<int> ptn(N, 0);
vector<int> pos(N, 0); for (int i = 0; i < N; i++) {
ptn[i] = (i % 2 == 0 ? i + 1 : i - 1);
pos[row[i]] = i;
} for (int i = 0; i < N; i++) {
for (int j = ptn[pos[ptn[row[i]]]]; i != j; j = ptn[pos[ptn[row[i]]]]) {
swap(row[i], row[j]);
swap(pos[row[i]], pos[row[j]]);
res++;
}
} return res;
}

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 765. Couples Holding Hands 情侣牵手的更多相关文章

  1. 【LeetCode】765. Couples Holding Hands 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/couples- ...

  2. 765. Couples Holding Hands

    ▶ n 对夫妻共 2n 个人随机坐成一排,“交换其中某两人的位置” 称为一次操作,求最少的操作此次数,使 n 对夫妻两人都相邻.初始座位为非负整数列 D1n-1,其中值为 2k 和 2k+1 的两个元 ...

  3. Leetcode之并查集专题-765. 情侣牵手(Couples Holding Hands)

    Leetcode之并查集专题-765. 情侣牵手(Couples Holding Hands) N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手. 计算最少交换座位的次数,以便每对情侣可以并 ...

  4. Java实现 LeetCode 765 情侣牵手(并查集 || 暴力)

    765. 情侣牵手 N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手. 计算最少交换座位的次数,以便每对情侣可以并肩坐在一起. 一次交换可选择任意两人,让他们站起来交换座位. 人和座位用 0 ...

  5. [Swift]LeetCode765. 情侣牵手 | Couples Holding Hands

    N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum numb ...

  6. [LeetCode] Couples Holding Hands 两两握手

    N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum numb ...

  7. LeetCode-765.情侣牵手

    N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手. 计算最少交换座位的次数,以便每对情侣可以并肩坐在一起. 一次交换可选择任意两人,让他们站起来交换座位. 人和座位用 0 到 2N-1 的整 ...

  8. LeetCode765. Couples Holding Hands

    N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum numb ...

  9. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

随机推荐

  1. sql中如何获取一条数据中所有字段的名称和值

    declare ) ) --获取表的列名 ,),filename INTO #templist FROM (select cl.name as filename from sys.tables AS ...

  2. 《逆袭团队》第九次团队作业【Beta】Scrum meeting 3

    项目 内容 软件工程 任课教师博客主页链接 作业链接地址 团队作业9:Beta冲刺与团队项目验收 团队名称 逆袭团队 具体目标 (1)掌握软件黑盒测试技术:(2)学会编制软件项目总结PPT.项目验收报 ...

  3. 2、HDFS交互式Shell

    管理模式 bin/hdfs dfsadmin ## run a hdfs admin client bin/hdfs dfsadmin -report ##报告信息 bin/hdfs dfsadmin ...

  4. codeforcesC - Berry Jam(折半枚举+1-1序列前后缀和)

    Educational Codeforces Round 78 (Rated for Div. 2) C - Berry Jam C. Berry Jam time limit per test 2 ...

  5. ssh集成

    导入pom依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w ...

  6. 验证符号文件的又一方法(!itoldyouso)

    如果您正在开发软件,很可能遇到了“不匹配的PDB”调试器错误.当您将调试器指向错误的符号路径时,通常会发生这种情况. 但有时你确信你所指向的符号是正确的符号,这让你想知道为什么调试器认为这些符号不匹配 ...

  7. 在Matlab中的tick可以调整方向

    需要将axis对话框的More property打开,修改TickDir,可从In改成Out.

  8. 【18NOIP普及组】对称二叉树(信息学奥赛一本通 1981)(洛谷 5018)

    [题目描述] 一棵有点权的有根树如果满足以下条件,则被轩轩称为对称二叉树: 1.二叉树: 2.将这棵树所有节点的左右子树交换,新树和原树对应位置的结构相同且点权相等. 下图中节点内的数字为权值,节点外 ...

  9. 设计模式——<面向对象设计原则以及23种设计模式分类>

    一.面向对象八大设计原则: 1.依赖倒置原则(DIP) 高层模块(稳定)不应该依赖于低层模块(变化),二者都应该依赖于抽象(稳定) . 抽象(稳定)不应该依赖于实现细节(变化) ,实现细节应该依赖于抽 ...

  10. D3.js的v5版本入门教程(第七章)—— 比例尺的使用

    D3.js的v5版本入门教程(第七章) 比例尺在D3.js中是一个很重要的东西,我们可以这样理解d3.js中的比例尺——一种映射关系,从domain映射到range域(为什么会是domain和rang ...