public int findPairs(int[] nums, int k) {
if(k<0  nums.length<=1){
return 0;
}
Arrays.sort(nums);
int count = 0;
int left = 0;
int right = 1;
while(right<nums.length){
int firNum = nums[left];
int secNum = nums[right];
// If less than k, increase the right index
if(secNumfirNum<k){
right++;
}
// If larger than k, increase the left index
else if(secNum  firNum>k){
left++;
}
// If equal, move left and right to next different number
else{
count++;
while(left<nums.length && nums[left]==firNum){
left++;
}
while(right<nums.length && nums[right]==secNum){
right++;
}
}
//left and right should not be the same number
if(right==left){
right++;
}
}
return count;
}
Selfexplained AC Java Sliding Window



We can get the count of each number and deal with k == 0 and k > 0 cases separately. Python has a handy Counter datatype :)
In [1]: import collections In [2]: a = [10, 10, 20, 20, 20, 30] In [3]: collections.Counter(a) Out[3]: Counter({10: 2, 20: 3, 30: 1})
class Solution(object): def findPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums_count = collections.Counter(nums) return sum(k > 0 and x + k in nums_count or k == 0 and nums_count[x] > 1 for x in set(nums))