c语言sscanf函数的用法是什么
267
2022-08-27
[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: 8Explanation: 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: 16Explanation: 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 <= 10001 <= nums[i] <= 104All 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)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~