同积元组
C++ 的解题代码,使用哈希表来统计每对数的乘积,以及乘积出现的次数。注意这里使用的是 unordered_map
:
cpp#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int tupleSameProduct(vector<int>& nums) {
int n = nums.size();
unordered_map<int, int> productCount;
int result = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int product = nums[i] * nums[j];
result += 8 * productCount[product];
productCount[product]++;
}
}
return result;
}
int main() {
// 示例用法
vector<int> nums = {2, 3, 4, 6};
int result = tupleSameProduct(nums);
cout << "Number of tuples: " << result << endl;
return 0;
}
这个解法的基本思路是,遍历所有可能的两对数的组合,计算它们的乘积,并使用哈希表记录乘积出现的次数。由于要求 a * b = c * d,所以对于每个乘积,可以生成8个符合条件的组合。最后将所有符合条件的组合数加起来即可。
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!