[LeetCode] Tuple with Same Product

1726. Tuple with Same Product

Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a b = c d where a, b, c, and d are elements of nums, and a != b != c != d.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int tupleSameProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());

map<int, int> multiplies;
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
multiplies[nums[i] * nums[j]]++;
}
}
int answer = 0;
for(auto it = multiplies.begin(); it != multiplies.end(); it++) {
answer += ((it->second) * (it->second - 1))<< 2;
}

return answer;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/17/PS/LeetCode/tuple-with-same-product/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.