https://leetcode.com/problems/count-array-pairs-divisible-by-k/
要想的更清楚一些,抓住gcd的性质
个人解答
class Solution:def countPairs(self, nums: List[int], k: int) -> int:c = Counter([math.gcd(x, k) for x in nums])res = 0for x in c:for y in c:if x * y % k == 0 and x <= y:if x < y:res += c[x] * c[y]else:res += c[x] * (c[x] - 1) // 2return res
题目分析
比较容易想到,需要依靠gcd的特性,减少遍历计算的工作量。
一开始的想法是,x * y % k == 0,那么满足条件的x和y,能凑够k的因数即可,所以先找出x与k共有的所有因数,再遍历y来判断:
class Solution:def countPairs(self, nums: List[int], k: int) -> int:d = {}for x in range(2, k + 1):if k % x == 0:d[x] = 0for n in nums:for x in d:if n % x == 0:d[x] += 1d[1] = len(nums)print(d)res = 0for n in nums:x = k // math.gcd(n, k)if n % x == 0:res += d[x] - 1else:res += d[x]return res // 2
但其实,只要两个的gcd满足,那么肯定是可以的,所以不用计算所有因数,只要看gcd即可,就像题解中描述的那样。
还是很妙的!
