[765][困难][并查集][贪心] 情侣牵手
题目描述
输入: row = [0, 2, 1, 3]
输出: 1
解释: 我们只需要交换row[1]和row[2]的位置即可。输入: row = [3, 2, 0, 1]
输出: 0
解释: 无需交换座位,所有的情侣都已经可以手牵手了。解题思路
贪心 + 哈希
并查集
最后更新于
输入: row = [0, 2, 1, 3]
输出: 1
解释: 我们只需要交换row[1]和row[2]的位置即可。输入: row = [3, 2, 0, 1]
输出: 0
解释: 无需交换座位,所有的情侣都已经可以手牵手了。最后更新于
class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
length = len(row)
n = length // 2
mapping = {num: i for i, num in enumerate(row)}
count = 0
for i in range(n):
left, right = i * 2, i * 2 + 1
lnum, rnum = row[left], row[right]
other = lnum ^ 1
if rnum != other:
count += 1
other_index = mapping[other]
row[right], row[other_index] = row[other_index], row[right]
mapping[rnum] = other_index
return countclass Union:
def __init__(self, n):
self.roots = list(range(n))
def find(self, i):
if self.roots[i] == i:
return i
self.roots[i] = self.find(self.roots[i])
return self.roots[i]
def union(self, a, b):
self.roots[self.find(a)] = self.find(b)
def connected(self, a, b):
return self.find(a) == self.find(b)
class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
n = len(row)
union = Union(n // 2)
for i in range(n // 2):
left, right = i * 2, i * 2 + 1
lidx, ridx = row[left] // 2, row[right] // 2
if lidx != ridx:
union.union(lidx, ridx)
count, seen = 0, set()
for i in range(n // 2):
index = union.find(i)
if index not in seen:
seen.add(index)
count += 1
return n // 2 - count