Skip to content

Latest commit

 

History

History
40 lines (34 loc) · 895 Bytes

2006.差的绝对值为-k-的数对数目.md

File metadata and controls

40 lines (34 loc) · 895 Bytes

2006.差的绝对值为-k-的数对数目

/*
 * @lc app=leetcode.cn id=2006 lang=typescript
 *
 * [2006] 差的绝对值为 K 的数对数目
 */

// @lc code=start
function countKDifference(nums: number[], k: number): number {}
// @lc code=end

解法 1: 哈希表

function countKDifference(nums: number[], k: number): number {
  const map = new Map<number, number>()
  let res = 0
  for (const num of nums) {
    res += map.get(num + k) ?? 0
    res += map.get(num - k) ?? 0
    map.set(num, (map.get(num) ?? 0) + 1)
  }
  return res
}

Case

test.each([
  { input: { nums: [1, 2, 2, 1], k: 1 }, output: 4 },
  { input: { nums: [1, 3], k: 3 }, output: 0 },
  { input: { nums: [3, 2, 1, 5, 4], k: 2 }, output: 3 },
])('input: nums = $input.nums, k = $input.k', ({ input: { nums, k }, output }) => {
  expect(countKDifference(nums, k)).toEqual(output)
})