functupleSameProduct(nums []int)int { n := len(nums) cnt := make(map[int]int) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ {// j +1 不要重复 cnt[nums[i] * nums[j]]++ // 使用map 遍历每次乘积对应次数 } } ans := 0 for _, v := range cnt { ans += v * (v - 1) * 4 }
[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: inttupleSameProduct(vector<int>& nums){ int n = nums.size(); int ans = 0; unordered_map<int, int> cnt; for (int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { cnt[nums[i] * nums[j]]++; } } for (auto &[k, v] : cnt) { ans += v * (v - 1) * 4; } return ans; } };
[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Solution: def tupleSameProduct(self, nums: List[int]) -> int: n = len(nums) maps = dict()
for i in range(n): for j in range(i+1,n): if nums[i]*nums[j] in maps: maps[nums[i] * nums[j]] += 1 else: maps[nums[i] * nums[j]] = 1
ans = 0 for _, v in maps.items(): ans += v*(v-1) *4 return ans