YSMull
<-- algorithm



原题链接

哈希表

var countKDifference = function(nums, k) {
  let countMap = new Map();
  nums.forEach(n => {
      countMap.set(n, (countMap.get(n) || 0) + 1);
  });
  let ans = 0;
  for (let n of countMap.keys()) {
      ans += (countMap.get(n) || 0) * (countMap.get(n + k) || 0)
  }
  return ans;
};

滑动窗口

var countKDifference = function(nums, k) {
  let countMap = {};
  nums.forEach(n => {
    countMap[n] = (countMap[n] || 0) + 1;
  });
  nums = [...new Set(nums)].sort((a,b) => a - b);
  let i = 0, j = 1;
  let ans = 0;
  while (j < nums.length) {
    if (i == j) {
        j++;
        continue;
    }
    let abs = nums[j] - nums[i];
    if (abs === k) {
        ans += countMap[nums[j]] * countMap[nums[i]];
        i++;j++;
    } else if (abs > k) {
        i++;
    } else {
        j++;
    }
  }
  return ans;
};