1726. 同积元组

1726. 同积元组_第1张图片


1726. 同积元组
难度: 中等
来源: 每日一题 2023.10.19

给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 abcd 都是 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)

提示:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^4
  • nums 中的所有元素 互不相同
class Solution {
    public int tupleSameProduct(int[] nums) {

    }
}

分析与题解

  • HashMap

    这个题目如果用两层暴力遍历方案一般会超时, 昨天晚上12点时看到这个题只想到了暴力模拟方案, 今天早上想了一下, 为啥不用HashMap来存储乘积呢?

    所以, 只要对于能形成 乘积A 的两两元素个数大于等于 2 就可以形成 四个符合题意的元组 .

    有了这样的思路之后, 我们首先构建乘积的HashMap, 其中key为乘积值, value为能形成该乘积的两两元素的个数.

    // 创建一个HashMap 来存储两个数的乘积, 其中乘积是key, 个数是value
    HashMap cache = new HashMap<>();
    for(int i = 0; i < nums.length; i++) {
        for(int j = i + 1; j < nums.length; j++) {
            int count = cache.getOrDefault(nums[i] * nums[j], 0);
            count++;
            cache.put(nums[i] * nums[j], count);
        }
    }
    

    然后利用 排列的思想, 从n个中元素每次选出2个元素, 一共有多少种排列? 答案是 n * (n-1). 所以对于乘积A, 假设有 n 个两两元素能形成 乘积A, 那么一共有 n * (n - 1) * 4 个元素.

    int result = 0;
    for(Integer key : cache.keySet()) {
        int count = cache.getOrDefault(key, 0);
        if (count <= 1) {
            continue;
        }
        int permutationCount = count * (count - 1);
        result += permutationCount * 2 * 2;
    }
    

    接下来, 我们一起看一下整体的解题思路.

    class Solution {
        public int tupleSameProduct(int[] nums) {
            // 创建一个HashMap 来存储两个数的乘积, 其中乘积是key, 个数是value
            HashMap cache = new HashMap<>();
            for(int i = 0; i < nums.length; i++) {
                for(int j = i + 1; j < nums.length; j++) {
                    int count = cache.getOrDefault(nums[i] * nums[j], 0);
                    count++;
                    cache.put(nums[i] * nums[j], count);
                }
            }
            int result = 0;
            for(Integer key : cache.keySet()) {
                int count = cache.getOrDefault(key, 0);
                if (count <= 1) {
                    continue;
                }
                int permutationCount = count * (count - 1);
                result += permutationCount * 2 * 2;
            }
            return result;
        }
    }
    

    复杂度分析:

    • 时间复杂度: O(n²), 时间复杂度与数组长度相关. 由于两层遍历, 时间复杂度为 O(n²)
    • 空间复杂度: O(n²), n 是数组的长度, 乘积可能的个数就可能是 , HashMap开辟的空间则为

    结果如下所示.

你可能感兴趣的:(LeetCode的秃头之路,算法,HashMap)