5243. 同积元组

难度中等1

给你一个由 不同 正整数组成的数组 nums ,请你返回满足 a * b = c * d 的元组 (a, b, c, d) 的数量。其中 abc 和 d 都是 nums 中的元素,且 a != b != c != d 。

示例 1:

输入:nums = [2,3,4,6]
输出:8
解释:存在 8 个满足题意的元组:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (3,4,2,6) , (3,4,6,2) , (4,3,6,2)

示例 2:

输入:nums = [1,2,4,5,10]
输出:16
解释:存在 16 个满足题意的元组:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,4,5)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)

示例 3:

输入:nums = [2,3,4,6,8,12]
输出:40

示例 4:

输入:nums = [2,3,5,7]
输出:0

提示:

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

实际上对于每个可能的 (a, b, c, d)不同的排列就必有8个组合,因此只需超出不相同的a*b=c*d的数量*8即为结果。

方法1:暴力解法(超时)

遍历所有可能的组合方式,判断是否满足,并计数

class Solution {
public:
	int tupleSameProduct(vector<int>& nums) {
		sort(nums.begin(), nums.end());
		int res = 0;
		for (int i = 0; i < nums.size() - 3; ++i) {
			for (int j = nums.size() - 1; j > 2; --j) {
				double Ji = nums[i] * nums[j];
				for (int k = i + 1; k < j && nums[k] < sqrt(Ji); ++k) {
					for (int p = j - 1; p > k; --p) {
						if (Ji == nums[k] * nums[p])
							res += 8;
						else if (Ji > nums[k] * nums[p])
							break;
					}
				}
			}
		}
		return res;
	}
};

方法二:动态规划(AC)

计算所有不同两个数相乘的结果,并将结果保存至map结构中,其中所得数量大于1的即说明有不同的两个数相乘相等,其中两两组合的数量即为该乘机结果对应的满足a*b=c*d的数量

class Solution {
public:
	int tupleSameProduct(vector<int>& nums) {
		// sort(nums.begin(), nums.end());
		int res = 0;
		map<int, int>save;
		for (int i = 0; i < nums.size(); ++i) {
			for (int j = i + 1; j < nums.size(); ++j) {
				save[nums[i] * nums[j]]++;
			}
		}
		for (map<int, int>::iterator it = save.begin(); it != save.end(); it++) {
			// cout << it->first<< ' ' << it->second<<endl;
			if (it->second > 1) {
				int s = 0, cout = it->second - 1;
				while (cout != 0) {
					s += cout;
					cout--;
				}
				res += s * 8;
			}
		}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/Yanpr919/article/details/112749048