题目:
给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 a、b、c 和 d 都是 nums 中的元素,且 a != b != c != d 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/tuple-with-same-product
解题重要思路:
统计在nums中所有两个数的乘积出现的频率,若出现频率n大于1,则说明有满足条件的数,再由从n对数中选出两个,共个,两对的数在通过在公式a*b = c*d上变化位置共有8种情况,最后元组的个数为
个。
解题答案
class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
d = {}
length = len(nums)
for i in range(0, length):
for j in range(i + 1,length):
try:
d[nums[i] * nums[j]] = d[nums[i] * nums[j]] + 1
except:
d[nums[i] * nums[j]] = 1
res = 0
for i in d:
if d[i] > 1:
res += d[i] * (d[i] - 1) / 2
return int(res * 8)#注意转化为int类型