Python 中等价多米诺骨牌对的数量
pythonserver side programmingprogramming更新于 2025/11/4 3:24:17
假设我们有一个多米诺骨牌列表。每个多米诺骨牌都有两个数字。如果 a = c 且 b = d,或者 a = d 且 b = c,则两个多米诺骨牌 D[i] = [a, b] 和 D[j] = [c, d] 将相同。因此一个多米诺骨牌可以反转。我们必须返回 0 <= i < j < 多米诺骨牌长度的对数 (i, j),并确定 D[i] 等同于 D[j]。因此,如果多米诺骨牌列表为 [[1, 2], [2, 1], [3, 4], [6, 5]]。输出将为 1
为了解决这个问题,我们将遵循以下步骤 −
- 让 answer = 0
- 对于多米诺骨牌列表中的每一对 p −
- 对 p 进行排序
- 然后将每个多米诺骨牌的频率存储到 D 中
- 对于 D 中的值中的 b −
- answer := answer + (b * (b - 1))/2
- 返回 answer
示例
让我们看看下面的实现以便更好地理解 −
class Solution(object):
def numEquivDominoPairs(self, dominoes):
d = {}
ans = 0
for i in dominoes:
i.sort()
i = tuple(i)
if i not in d:
d[i]= 1
else:
d[i]+=1
for b in d.values():
ans += ((b*(b-1))//2)
return ans
ob1 = Solution()
print(ob1.numEquivDominoPairs([[1,2],[2,1],[3,4],[5,6], [4,3]]))
输入
[[1,2],[2,1],[3,4],[5,6],[4,3]]
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

