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 count
并查集
class 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