# Self-explained AC Java Sliding Window

• `````` 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(secNum-firNum<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;
}
``````

• Following part is not necessary.

``````if(right==nums.length-1){//reach the end
break;
}
``````

• @krisdu Thanks, you're right. :)

• I tried an array but got the wrong answer.
{-1,-1,-5,-1,-1}

• 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))
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.