题:给定数组nums和整数k,求数组中 满足|nums[i]-nums[j]| = k(i<j)的数对数目。
解:1. 直接两重循环
class Solution: def countKDifference(self, nums: List[int], k: int) -> int: cnt = 0 for i in range(len(nums)): for j in range(i+1,len(nums)): if abs(nums[j]-nums[i]) == k: cnt += 1 return cnt
2.哈希表
class Solution: def countKDifference(self, nums: List[int], k: int) -> int: cnt, ans = Counter(nums), 0 for key in cnt: if (key + k) in cnt: ans += cnt[key] * cnt[key + k] return ans