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. 微信小程序~页面跳转和路由

    一个小程序拥有多个页面,我们可以通过wx.navigateTo推入一个新的页面,如图3-6所示,在首页使用2次wx.navigateTo后,页面层级会有三层,我们把这样的一个页面层级称为页面栈.

  2. 关于c++中的类型转换符

    const_cast(链接) 用来去掉const或volatile属性 volatile: 用于并行设备的硬件寄存器(状态寄存器), 中断服务子程序中会访问到的非自动变量, 多线程中被几个任务共享的变 ...

  3. python Thread 函数

    构造方法: Thread(group=None, target=None, name=None, args=(), kwargs={})  group: 线程组,目前还没有实现,库引用中提示必须是No ...

  4. java项目部署到LIINUX

    天领导给个任务,把java项目部署到liunx服务器上.现记录步骤,方便以后查看.项目部署服务器步骤:服务器信息:弹性IP地址:xx.xx.xxx.xx账号:root密码:cjw@100 数据库信息: ...

  5. Apache Solr < 8.2.0远程命令执行漏洞(CVE-2019-0193)

    介绍:Apache Solr 是一个开源的搜索服务器.Solr 使用 Java 语言开发,主要基于 HTTP 和 Apache Lucene 实现. 漏洞原因:此次漏洞出现在Apache Solr的D ...

  6. 2019-2020-1 20199302《Linux内核原理与分析》第八周作业

    一.上课学习笔记 1.shell作用:①运行程序 ②重定向(输入/输出重定向) ③可编程(写脚本) 执行一个c程序时,如果切进另一个进程,会进入该进程而切不回原进程,所以需要为调用的进程创一个子进程. ...

  7. GoCN每日新闻(2019-10-14)

    GoCN每日新闻(2019-10-14) 1. 基于 Go 开源项目 MIMIO 的对象存储方案在探探的实践 https://mp.weixin.qq.com/s/YIKB_qAqqy6ydtFT_a ...

  8. 深度clone和浅clone

    首先等你有空的时候可以看这篇,要用可以看我这篇 https://www.cnblogs.com/echolun/p/7889848.html 1.有一点需要明确的是 深拷贝只是针对引用数据类型来说的, ...

  9. [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available

    原文链接https://blog.csdn.net/xiaomajia029/article/details/88320233 问题描述: 原因分析:在项目配置的时候,默认 npm 包导出的是运行时构 ...

  10. SubQuery优化

    https://zhuanlan.zhihu.com/p/60380557 子查询,分两种情况, 对于在From中的,称为‘derived table’,这种场景比较简单 对于在select,wher ...