给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 a、b、c 和 d 都是 nums 中的元素,且 a != b != c != d 。
示例 1:
输入: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) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
示例 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)
示例 3:
输入:nums = [2,3,4,6,8,12]
输出:40
示例 4:
输入:nums = [2,3,5,7]
输出:0
提示:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/tuple-with-same-product
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
设计一个哈希表,记录可能得到的各个积对应的数值组数 i,满足条件的元组数量即为 i * (i - 1) / 2。
class Solution {
public int tupleSameProduct(int[] nums) {
Map<Integer, Integer> pro = new HashMap<>();
int ans = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int key = nums[i] * nums[j];
Integer val = pro.get(key);
if (val != null) {
ans += val;
pro.put(key, ++val);
} else
pro.put(key, 1);
}
}
return ans << 3;
}
}
执行用时 :216 ms,在所有 Java 提交中击败了 96.44% 的用户;
内存消耗 :70.6 MB,在所有 Java 提交中击败了 32.07% 的用户。
class Solution {
public int tupleSameProduct(int[] nums) {
Map<Integer, Integer> pro = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int key = nums[i] * nums[j];
pro.put(key, pro.getOrDefault(key, 0) + 1);
}
}
int ans = 0;
for (int proNum : pro.values())
ans += proNum * (proNum - 1) * 4;
return ans;
}
}
执行用时 :259 ms,在所有 Java 提交中击败了 68.92% 的用户;
内存消耗 :70.4 MB,在所有 Java 提交中击败了 37.36% 的用户。
暂无。