[leetcode] 1726. Tuple with Same Product

Description

Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.

Example 1:

Input: nums = [2,3,4,6]
Output: 8
Explanation: There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)

Example 2:

Input: nums = [1,2,4,5,10]
Output: 16
Explanation: There are 16 valids tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,4,5)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)

Example 3:

Input: nums = [2,3,4,6,8,12]
Output: 40

Example 4:

Input: nums = [2,3,5,7]
Output: 0

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 104
  • All elements in nums are distinct.

分析

题目的意思是:这道题要求出有相同乘积的四个组合数。我看了一下思路,建立一个字典,对两两乘积进行统计,然后计算频率大于1的组合数就行了,公式维:

n*(n-1)/2*8

n为统计的频率.
因为每两对相同乘积的数,有8种不同的组合,所以排列组合一下为C(n,2)*8

代码

class Solution:
    def tupleSameProduct(self, nums: List[int]) -> int:
        n=len(nums)
        d=defaultdict(int)
        for i in range(n):
            for j in range(i+1,n):
                key=nums[i]*nums[j]
                d[key]+=1
        res=0
        # print(d)
        for k,v in d.items():
            if(v>1):
                res+=v*(v-1)/2*8
        return int(res)

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/114168554