---
# System prepended metadata

title: 2006. Count Number of Pairs With Absolute Difference K
tags: [Leetcode, Easy, HashMap]

---

# 2006. Count Number of Pairs With Absolute Difference K
###### tags: `Leetcode` `Easy` `HashMap`
Link: https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/description/

## Code
```java=
class Solution {
    public int countKDifference(int[] nums, int k) {
        int ans = 0;
        Map<Integer, Integer> cnt = new HashMap<>();
        for(int num:nums){
            ans += cnt.getOrDefault(num-k, 0)+cnt.getOrDefault(num+k, 0);
            cnt.put(num, cnt.getOrDefault(num, 0)+1);
        }
        return ans;
    }
}
```
```defaultdict()```括号里要设置默认值, 如果是int就会默认是0
```python=
class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        ans = 0
        cnt = defaultdict(int)
        for num in nums:
            ans += cnt[num-k]+cnt[num+k]
            cnt[num] += 1
        return ans
```