-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathK-diff.java
More file actions
34 lines (29 loc) · 819 Bytes
/
K-diff.java
File metadata and controls
34 lines (29 loc) · 819 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Arrays;
class Solution {
public int findPairs(int[] nums, int k) {
if (k < 0) return 0;
Arrays.sort(nums);
int n=nums.length;
int right=1;
int left=0;
int count=0;
//int arr= new int[n];
while(left<n && right<n){
if(left==right || nums[right]-nums[left]<k){
right++;
}
else if(nums[right]-nums[left]>k){
left++;
}
else{
count++;
left++;
right++;
// Skip duplicates
while (right < n && nums[right] == nums[right - 1]) right++;
while (left < right && nums[left] == nums[left - 1]) left++;
}
}
return count;
}
}