Article Directory
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.
Ideas:
- The hash table records the number of occurrences of all products.
- Product appears
k
times, 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(k−1)。 - 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;
}
};