Given an array of integers and an integerk, you need to find the number of unique k-diff pairs in the array. Here ak-diff pair is defined as an integer pair (i, j), where i and j are bothnumbers 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 inthe array, (1, 3) and (3, 5).
Although we have two 1s in the input, weshould 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 inthe 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 inthe array, (1, 1).
翻译:给定一个整数数组和一个整数k,你需要找到数组中唯一的k-diff对的数量。 这里,k-diff对被定义为整数对(i,j),其中i和j都是数组中的数字,它们的绝对差是k。
示例1:
输入:[3,1,4,1,5],k = 2
输出:2
说明:阵列中有两个2-diff对,(1,3)和(3,5)。
虽然我们在输入中有两个1,但我们应该只返回唯一对的数量。
示例2:
输入:[1,2,3,4,5],k = 1
输出:4
说明:阵列中有四个1-diff对,(1,2),(2,3),(3,4)和(4,5)。
示例3:
输入:[1,3,1,5,4],k = 0
输出:1
说明:阵列中有一个0-diff对,(1,1)。
分析:这题利用Set集合来解决,解决的思想和巧妙,以前做的leetcode也用到过(用的map集合)。直接比较集合中是否存在nums[i]-k或者nums[i]+k,然后为了避免重复,将结果放到set中。代码如下:
public class Solution {
public int findPairs(int[] nums, int k) {
if(nums==null||k<0) return 0;
Set<Integer>set=new HashSet<Integer>();
Set<Integer>setCount=new HashSet<Integer>();
for(inti=0;i<nums.length;i++){
if(set.contains(nums[i]-k))setCount.add(nums[i]);
if(set.contains(nums[i]+k))setCount.add(nums[i]+k);
set.add(nums[i]);
}
returnsetCount.size();
}
}