The problem is just a variant of 2-sum.

**Update:** Fixed a bug that can cause integer subtraction overflow.

**Update:** The code runs in `O(n log n)`

time, using `O(1)`

space.

```
public int findPairs(int[] nums, int k) {
int ans = 0;
Arrays.sort(nums);
for (int i = 0, j = 0; i < nums.length; i++) {
for (j = Math.max(j, i + 1); j < nums.length && (long) nums[j] - nums[i] < k; j++) ;
if (j < nums.length && (long) nums[j] - nums[i] == k) ans++;
while (i + 1 < nums.length && nums[i] == nums[i + 1]) i++;
}
return ans;
}
```