Skip to content

Commit

Permalink
update +
Browse files Browse the repository at this point in the history
  • Loading branch information
Fulong Ma committed Nov 11, 2023
1 parent f76b508 commit 9ce25a5
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions _posts/Algorithms/leetcode/2023-11-11-765. 情侣牵手.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
---
layout: post
category: leetcode
title: 765. 情侣牵手
tags: leetcode
---

## title
[problem link](https://leetcode.cn/problems/couples-holding-hands/description/?envType=daily-question&envId=2023-11-11)

`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
解释: 无需交换座位,所有的情侣都已经可以手牵手了。
```



**提示:**

- `2n == row.length`
- `2 <= n <= 30`
- `n` 是偶数
- `0 <= row[i] < 2n`
- `row` 中所有元素均**无重复**

## solution

It could save one exchange operation for one cycle.

Find the number of cycles.

```python

class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
n = len(row)
uf = UnionFind()
for i in range(0, n, 2):
uf.union(i,i+1)
m = n // 2
for i in range(0, n, 2):
uf.union(row[i], row[i+1])
cnt = 0
for i in range(n):
if uf.find(i) == i:
cnt += 1
return m - cnt
```

0 comments on commit 9ce25a5

Please sign in to comment.