leetCode刷题记录68_532_K-diff Pairs in an Array

/*****************************************************问题描述*************************************************
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
    Output: 2
    Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
    Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
    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).
Example 3:
    Input: [1, 3, 1, 5, 4], k = 0
    Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
给定一个整数数组和一个整数,在整数数组中找到两个值,它们的差等于给定的整数,求有多少对这样的2个值
/*****************************************************我的解答*************************************************
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findPairs = function(nums, k) {
    var resultArr = [];
    nums.sort((a,b) => {return a - b});
    for(var index1 = 0; index1 < nums.length; index1++)
    {
        for(var index2 = index1 + 1; index2 < nums.length; index2++)
        {
            if(Math.abs(nums[index1] - nums[index2]) == k)
            {
                if(resultArr.indexOf(nums[index1].toString() + nums[index2].toString()) == -1)
                {
                    resultArr.push(nums[index1].toString() + nums[index2].toString());
                }    
            }    
        }    
    }
    return resultArr.length;
};
console.log(findPairs([1, 2, 3, 4, 5],1));
 

发布了135 篇原创文章 · 获赞 10 · 访问量 6254

猜你喜欢

转载自blog.csdn.net/gunsmoke/article/details/89080917