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.
function findPairs(nums,k) {
var count = 0;
var obj = {};
if(nums.length < 2 || k < 0) {
return 0
}
nums.sort(function(a, b){
if (a > b) {
return 1
}else if(a < b){
return -1
}else{
return 0
}
});
for (var i = 0; i < nums.length; i++) {
var key = nums[i] - k;
if (k > 0) {
if (obj[key] && nums[i] != nums[i - 1]) {
count++;
}
obj[nums[i]] = 1
}else{
if (obj[key]) {
if(obj[key] == 1){
count++;
obj[nums[i]] = 2;
}
}else{
obj[nums[i]] = 1
}
}
}
return count
}