题目描述
给定一个由 不同 正整数组成的数组 nums
,请你返回满足 a * b = c * d
的元组 (a, b, c, d)
的数量。其中 a
、b
、c
和 d
都是 nums
中的元素,且 a != b != c != d
。
样例
输入:nums = [2,3,4,6]
输出:8
解释:存在 8 个满足题意的元组:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (3,4,2,6) , (3,4,6,2) , (4,3,6,2)
输入:nums = [1,2,4,5,10]
输出:16
解释:存在 16 个满足题意的元组:
(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)
输入:nums = [2,3,4,6,8,12]
输出:40
输入:nums = [2,3,5,7]
输出:0
限制
1 <= nums.length <= 1000
1 <= nums[i] <= 10^4
nums
中的所有元素 互不相同。
算法
(哈希表) $O(n^2)$
- 建立哈希表,记录构成每个乘积的无序数对的数量。
- 因为所有元素互不相同,所以在给定的乘积下,
(a, b) = (c, d)
时可以获得 4 种元组。
时间复杂度
- 初始化哈希表需要 $O(n^2)$ 的时间,遍历哈希表计算答案需要 $O(n^2)$ 的时间。
- 故总时间复杂度为 $O(n^2)$。
空间复杂度
- 需要 $O(n^2)$ 的空间存储哈希表。
C++ 代码
class Solution {
public:
int tupleSameProduct(vector<int>& nums) {
unordered_map<int, int> hash;
const int n = nums.size();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
hash[nums[i] * nums[j]]++;
int ans = 0;
for (const auto &it : hash)
ans += it.second * (it.second - 1) * 4;
return ans;
}
};