1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// @Title: 差的绝对值为 K 的数对数目 (Count Number of Pairs With Absolute Difference K)
// @Author: 15816537946@163.com
// @Date: 2022-02-09 11:09:22
// @Runtime: 8 ms
// @Memory: 4 MB
func countKDifference(nums []int, k int) int {
    counter := map[int]int{}
    var ans int

    for _, num := range nums {
        ans +=counter[num-k]+counter[num+k]
        counter[num]++
    }

    return ans
}