📅  最后修改于: 2023-12-03 15:36:47.367000             🧑  作者: Mango
给定一个长度为N的数组A和一个整数K,计算由三个元素组成的三元组(i,j,k),使得i<j<k并且Ai,Aj和Ak的最大公因数均为K。
因为O(N^2)时间复杂度的算法比O(N^3)更优,因此以下内容将更多地介绍哈希表解决方案。
def count_triplets(arr, k):
n = len(arr)
hash_map = {}
for i in range(n):
if arr[i] % k == 0:
if arr[i] in hash_map:
hash_map[arr[i]] += 1
else:
hash_map[arr[i]] = 1
count = 0
for i in range(len(hash_map)):
a = list(hash_map.keys())[i]
for j in range(i, len(hash_map)):
b = list(hash_map.keys())[j]
c = k - a - b
if c in hash_map and b <= c:
if a == b == c:
count += hash_map[a] * (hash_map[a] - 1) * (hash_map[a] - 2) // 6
elif a == b:
count += hash_map[c] * hash_map[a] * (hash_map[a] - 1) // 2
elif a == c:
count += hash_map[b] * hash_map[a] * (hash_map[a] - 1) // 2
elif b == c:
count += hash_map[a] * hash_map[b] * (hash_map[b] - 1) // 2
else:
count += hash_map[a] * hash_map[b] * hash_map[c]
return count