Skip to content

Latest commit

 

History

History
43 lines (35 loc) · 910 Bytes

532.数组中的-k-diff-数对.md

File metadata and controls

43 lines (35 loc) · 910 Bytes

532.数组中的-k-diff-数对

/*
 * @lc app=leetcode.cn id=532 lang=typescript
 *
 * [532] 数组中的 k-diff 数对
 */

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

解法 1: 哈希表

function findPairs(nums: number[], k: number): number {
  const set = new Set(),
    res = new Set()

  for (let a of nums) {
    if (set.has(a - k)) res.add(a - k)
    if (set.has(a + k)) res.add(a)
    set.add(a)
  }

  return res.size
}

Case

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