-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathK_diffPairsinanArray_532.java
More file actions
47 lines (42 loc) · 1.14 KB
/
Copy pathK_diffPairsinanArray_532.java
File metadata and controls
47 lines (42 loc) · 1.14 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package Array;
import java.util.*;
public class K_diffPairsinanArray_532 {
public int findPairs(int[] nums, int k) {
Arrays.sort(nums);
Map<Integer,Integer> pair=new HashMap<>();
Map<Integer,Integer> res=new HashMap<>();
int count=0;
for(int n:nums){
int m=n+k;
if(!pair.containsKey(n)){
pair.put(m,n);
}else{
res.put(m,n);
pair.put(m,n);
}
}
return res.size();
}
public int findPairs1(int[] nums, int k) {
if(k<0 || nums.length<2)
return 0;
Arrays.sort(nums);
int i=0,j=1,result=0;
while(i<nums.length && j<nums.length)
{
if(nums[j]-nums[i]==k)
{
result++;
i++;j++;
while(j<nums.length && nums[j] == nums[j-1])
j++;
} else if(nums[j]-nums[i]>k){
i++;
if(i==j)
j++;
} else
j++;
}
return result;
}
}