|
| 1 | +# [1726. 同积元组](https://leetcode.cn/problems/tuple-with-same-product/) |
| 2 | + |
| 3 | +- 标签:数组、哈希表 |
| 4 | +- 难度:中等 |
| 5 | + |
| 6 | +## 题目链接 |
| 7 | + |
| 8 | +- [1726. 同积元组 - 力扣](https://leetcode.cn/problems/tuple-with-same-product/) |
| 9 | + |
| 10 | +## 题目大意 |
| 11 | + |
| 12 | +**描述**:给定一个由不同正整数组成的数组 $nums$。 |
| 13 | + |
| 14 | +**要求**:返回满足 $a \times b = c \times d$ 的元组 $(a, b, c, d)$ 的数量。其中 $a$、$b$、$c$ 和 $d$ 都是 $nums$ 中的元素,且 $a \ne b \ne c \ne d$。 |
| 15 | + |
| 16 | +**说明**: |
| 17 | + |
| 18 | +- $1 \le nums.length \le 1000$。 |
| 19 | +- $1 \le nums[i] \le 10^4$。 |
| 20 | +- $nums$ 中的所有元素互不相同。 |
| 21 | + |
| 22 | +**示例**: |
| 23 | + |
| 24 | +- 示例 1: |
| 25 | + |
| 26 | +```python |
| 27 | +输入:nums = [2,3,4,6] |
| 28 | +输出:8 |
| 29 | +解释:存在 8 个满足题意的元组: |
| 30 | +(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) |
| 31 | +(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) |
| 32 | +``` |
| 33 | + |
| 34 | +- 示例 2: |
| 35 | + |
| 36 | +```python |
| 37 | +输入:nums = [1,2,4,5,10] |
| 38 | +输出:16 |
| 39 | +解释:存在 16 个满足题意的元组: |
| 40 | +(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) |
| 41 | +(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) |
| 42 | +(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) |
| 43 | +(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) |
| 44 | +``` |
| 45 | + |
| 46 | +## 解题思路 |
| 47 | + |
| 48 | +### 思路 1:哈希表 + 数学 |
| 49 | + |
| 50 | +1. 二重循环遍历数组 $nums$,使用哈希表 $cnts$ 记录下所有不同 $nums[i] \times nums[j]$ 的结果。 |
| 51 | +2. 因为满足 $a \times b = c \times d$ 的元组 $(a, b, c, d)$ 可以按照不同顺序进行组和,所以对于 $x$ 个 $nums[i] \times nums[j]$,就有 $C_x^2$ 种组和方法。 |
| 52 | +3. 遍历哈希表 $cnts$ 中所有值 $value$,将不同组和的方法数累积到答案 $ans$ 中。 |
| 53 | +4. 遍历完返回答案 $ans$。 |
| 54 | + |
| 55 | +### 思路 1:代码 |
| 56 | + |
| 57 | +```Python |
| 58 | +class Solution: |
| 59 | + def tupleSameProduct(self, nums: List[int]) -> int: |
| 60 | + cnts = Counter() |
| 61 | + size = len(nums) |
| 62 | + for i in range(size): |
| 63 | + for j in range(i + 1, size): |
| 64 | + product = nums[i] * nums[j] |
| 65 | + cnts[product] += 1 |
| 66 | + |
| 67 | + ans = 0 |
| 68 | + for key, value in cnts.items(): |
| 69 | + ans += value * (value - 1) * 4 |
| 70 | + |
| 71 | + return ans |
| 72 | +``` |
| 73 | + |
| 74 | +### 思路 1:复杂度分析 |
| 75 | + |
| 76 | +- **时间复杂度**:$O(n^2)$,其中 $n$ 表示数组 $nums$ 的长度。 |
| 77 | +- **空间复杂度**:$O(n^2)$。 |
| 78 | + |
0 commit comments