leecode 765 情侣牵手问题,并查集+问题转换能力
2022/2/3 6:14:34
本文主要是介绍leecode 765 情侣牵手问题,并查集+问题转换能力,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
分析:假设有 N对情侣,假设有 K 个集合(存在情侣的集合),(偶数,偶数+1)为一个元素最少的集合这种情况符合题意不需要交换。假设每个集合里面有 m1,m2, m3.......mk个元素,需要进行m1-1,m2-1, m3-1.......mk-1次交换,求和得到本题答案为N - K
class UnionSet: def __init__(self, n): self.father = list(range(n)) def find(self, ind): #找寻元素的根节点 if self.father[ind] == ind: return ind self.father[ind] = self.find(self.father[ind]) return self.father[ind] def union(self, x, y): #将y并入x类 root_x = self.find(x) #x位置元素,根节点为root_x编号元素 root_y = self.find(y) #y位置元素,根节点为root_y编号元素 if root_x != root_y: self.father[root_y] = root_x #把root_y编号元素的父节点,替换为root_x return def isConnection(self, x, y): return self.find(x) == self.find(y) class Solution: def minSwapsCouples(self, row: List[int]) -> int: n = len(row) // 2 us = UnionSet(n) for i in range(0, len(row) , 2): left = row[i] // 2 right = row[i+1] // 2 if left != right: us.union(left, right) set_count = 0 for i in range(n): if us.find(i) == i: set_count += 1 return n - set_count
这篇关于leecode 765 情侣牵手问题,并查集+问题转换能力的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升