[M hash] lc1726. Same product tuple (hash+count+weekly contest 224_2)

1. Source of the subject

Link: 1726. Tuples of the same product

2. Topic analysis

Counting problem. I didn't see the question clearly, and kept thinking about how to remove the repetition. As a result, the question required no repetitive elements... The weekly competition was quite unsuccessful.
Insert picture description here
Ideas:

  • The hash table records the number of occurrences of all products.
  • Product appears ktimes, would constitute 8 × C k 2 8 \ times C_k ^ 28×Ck2The same product tuples. Where C k 2 = k (k − 1) 2 C_k^2=\frac {k(k-1)} 2Ck2=2k(k1)
  • For each product, find the corresponding number of tuples of the same product.

  • Time complexity : O (n 2) O(n^2)O ( n2)
  • Space complexity : O (n) O(n)O ( n )

Code:

class Solution {
    
    
public:
    int tupleSameProduct(vector<int>& nums) {
    
    
        int n = nums.size();
        unordered_map<int, int> hash;
        for (int i = 0; i < n; i ++ ) 
            for (int j = i + 1; j < n; j ++ ) 
                hash[nums[i] * nums[j]] ++ ;
        int res = 0;
        for (auto& [p, k] : hash) 
            res += k * (k - 1) / 2 * 8;
        return res;
    }
};

Guess you like

Origin blog.csdn.net/yl_puyu/article/details/112769718