- 题目链接:https://leetcode-cn.com/problems/count-number-of-pairs-with-absolute-difference-k/
- 题目描述
给你一个整数数组 nums 和一个整数 k ,请你返回数对 (i, j) 的数目,满足 i < j 且 |nums[i] - nums[j]| == k 。
|x| 的值定义为:
如果 x >= 0 ,那么值为 x 。
如果 x < 0 ,那么值为 -x 。
 
 
输入:nums = [1,2,2,1], k = 1
输出:4
解释:差的绝对值为 1 的数对为:
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
 
 
- 数据规模较小,直接暴力即可
- 使用哈希表
 public int countKDifference(int[] nums, int k) {
     int num = 0;
     for (int i=0;i<nums.length;i++){
         for (int j=i+1;j<nums.length;j++){
             if (Math.abs(nums[i]-nums[j])==k)
                 num++;
         }
     }
     return num;
 }
 
 
public int countKDifference(int[] nums, int k) {
    int res = 0, n = nums.length;
    Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();
    for (int j = 0; j < n; ++j) {
        res += cnt.getOrDefault(nums[j] - k, 0) + cnt.getOrDefault(nums[j] + k, 0);
        cnt.put(nums[j], cnt.getOrDefault(nums[j], 0) + 1);
    }
    return res;
}
 
 
public int countKDifference(int[] nums, int k) {
    int[] cnts = new int[110];
    int n = nums.length, ans = 0;
    for (int i = 0; i < n; i++) {
        int t = nums[i];
        if (t - k >= 1) ans += cnts[t - k];
        if (t + k <= 100) ans += cnts[t + k];
        cnts[t]++;
    }
    return ans;
}