2023/10/19

120 阅读1分钟

1726. 同积元组

算法掌握:

  • 判断时间复杂度
  • 暴力,hash

解题思路:

首先我们先看数据范围

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1e4
  • nums 中的所有元素 互不相同

我们知道,程序1s大约可以处理 1e8条记录 这里直接暴力双循环把所有两两相互乘积的数用hash表记录一下它们的个数,然后通过不重复用排列组合的思想计算时间复杂度也才 n ^ 2 nums[i] ^ 2 也不会爆 int

每一组 积的个数来排列的种类 -> (p(2, 2) + p(2, 2)) * c(2, cnt)

java code:

class Solution {
    public int tupleSameProduct(int[] nums) {
        int n = nums.length;
        if(n < 4) return 0;
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < n; i++){
            for(int j = i + 1; j < n; j++){
                int x = nums[i] * nums[j];
                map.put(x, map.getOrDefault(x, 0) + 1);
            }
        }
        int res = 0;
        for(int x : map.values()){
            res += 4 * x * (x - 1);
        }
        return res;
    }
}

c++ code

class Solution {
public:
    int tupleSameProduct(vector<int>& nums) {
        int size = nums.size();
        if(size < 4) return 0;
        unordered_map<int, int> mp;
        //x = 2(x表示12有两组)  (p(2, 2) + p(2, 2)) * p(2, x) = (2 + 2) * (1 * 2) = 8 种 
        for(int i = 0; i < size; i++){
            for(int j = i + 1; j < size; j++){
                mp[nums[i] * nums[j]] ++;
            }
        }

        int res = 0;
        for(const auto& x : mp){
            res += 4 * x.second * (x.second - 1);
        }
        return res;
    }
};