0
点赞
收藏
分享

微信扫一扫

每日一题 2006. 差的绝对值为 K 的数对数目


题:给定数组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

举报

相关推荐

0 条评论