Question:

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example:

  1. Input: [3, 1, 4, 1, 5], k = 2
  2. Output: 2
  3. Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
  4. Although we have two 1s in the input, we should only return the number of unique pairs.
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).


Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

Solution:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findPairs = function(nums, k) {
    // 前后2个元素相减等于k , 使用冒泡算法,时间复杂度 O(n^2) , 使用对象索引去重
    let kDiffNum = 0;
    let diffMap = {};
    for ( let i = 0; i<nums.length; i++ ) {
        for ( let j = i + 1; j < nums.length; j++ ) {
            if ( Math.abs( nums[j] - nums[i] ) === k ) {
                if ( !diffMap[nums[j]+'-'+nums[i]] && !diffMap[nums[i]+'-'+nums[j]] ) {
                    diffMap[nums[j]+'-'+nums[i]] = 1;
                    diffMap[nums[i]+'-'+nums[j]] = 1;
                    kDiffNum++;
                }
            }
        }
    }
    return kDiffNum;
};

什么鬼
Runtime: 1496 ms, faster than 5.92% of JavaScript online submissions for K-diff Pairs in an Array.