-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek8 532 K-diff Pairs in an Array
More file actions
64 lines (55 loc) · 1.69 KB
/
week8 532 K-diff Pairs in an Array
File metadata and controls
64 lines (55 loc) · 1.69 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array.
//Here a k-diff pair is defined as an integer pair (i,j), where i and j are both numbers in the array and their absolute difference is K.
//Assumption 1: not sorted
//Assumption 2: duplicates
//Assumption 3: unique pairs
//Assumption 4: k can be smaller or equal to 0
//HashMap
public int findPairs(int[] nums, int k){
if(nums == null || nums.length <= 1){
return 0;
}
Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
int count = 0;
for (int n:nums){
countMap.put(n, countMap.getOrDefault(n,0) + 1);
}
for (Map.Entry<Integer, Integer> entry: countMap.entrySet()){
if(k != 0){
if(countMap.containsKey(entry.getKey() - k)){
count++;
}
}else{
if(entry.getValue() > 1){
count++;
}
}
}
return count;
}
//Two Pointers
public int findPairs(int[] nums, int k){
if(nums == 0 || nums.length <= 1){
return 0;
}
Arrays.sort(nums);
k = Math.abs(k);
int left = 0;
int right = 1;
int count = 0;
while(right < nums.length){
if(left >= right || nums[right] - nums[left] < k){
right++;
}else if(left > 0 && nums[left] == nums[left - 1] || nums[right] - nums[left] > k){
legt++;
}else {
right++;
count++;
}
}
return count;
}
//Summary -- Linear Structure --> Pointers
//1. Physical Meaning of Pointers:scanner or fixer
//2. In each iteration, how to deal with fixer? Not scanner
//3. Tricky: does fixer include itself?