leetcode 532. k-diff pairs in an array

给定一个整数数组和一个整数k,您需要找到数组中唯一的k-diff对的数量。这里k-diff对被定义为整数对(i,j),其中i和j都是数组中的数字,它们的绝对差是k。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int findPairs(int[] nums, int k) {
Arrays.sort(nums);
int len = nums.length;
if(len==0){
return 0;
}
int sum = 0;
Set<Integer> values = new HashSet<Integer>();
Set<Integer> result = new HashSet<Integer>();
values.add(nums[0]);
for(int i=1;i<len;i++){
if (values.contains(nums[i]-k)){
result.add(nums[i]-k);
}
values.add(nums[i]);
}
return result.size();
}
}