[LeetCode] 1726. Tuple with Same Product

发布时间 2023-10-21 07:18:52作者: CNoodle

Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where abc, 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 valid 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,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)

Constraints:

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

同积元组。

给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 abc 和 d 都是 nums 中的元素,且 a != b != c != d 。

思路是用 hashmap。注意题目里的这个要求,nums 数组中所有的元素都是互不相同的,所以我们可以像 two sum 那样用 hashmap<product, count> 先记录数组里有多少个不同的 a * b 组合, a * b 的结果我们暂且记为 product。因为 nums 里所有元素是互不相同的,所以如果有另外两个不是 a 和 b 的元素的乘积也等于 product 的话,我们就能找到这样一个四元组 (a, b, c, d) 了。

我们用 hashmap 把所有的不同 product 记录好之后,开始遍历每个 unique 的 key。对于当前这个 key (乘积) 而言,能凑成这个乘积的组合数 = count * (count - 1) / 2。为什么最后还要乘以 8,可以参照第一个例子,当我们能找到一个乘积为 12 的四元组的时候,这个四元组能构成 8 种不同的排列组合,所以要乘以 8。

时间O(n^2)

空间O(n)

Java实现

 1 class Solution {
 2     public int tupleSameProduct(int[] nums) {
 3         HashMap<Integer, Integer> map = new HashMap<>();
 4         for (int i = 0; i < nums.length; i++) {
 5             for (int j = i + 1; j < nums.length; j++) {
 6                 int product = nums[i] * nums[j];
 7                 map.put(product, map.getOrDefault(product, 0) + 1);
 8             }
 9         }
10 
11         int res = 0;
12         for (int key : map.keySet()) {
13             int val = map.get(key);
14             res += val * (val - 1) / 2 * 8;
15         }
16         return res;
17     }
18 }

 

LeetCode 题目总结