You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Similar approach as sum of 2 nummber to a given sum in an array. Special case of (k == 0) -> check for frequency of the number >= 2 as only (x-x) will give 0.
*/
classSolution {
publicintfindPairs(int[] nums, intk) {
Map<Integer, Integer> map = newHashMap<>();
for (intn : nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
intpairs = 0;
for (Integerkey : map.keySet()) {
intmapVal = map.getOrDefault(key+k, 0);
if (k == 0) {
if (mapVal > 1)
pairs += 1;
}
else {
if (mapVal > 0)
pairs += 1;
}
}
returnpairs;
}
}
// Problem : https://leetcode.com/problems/k-diff-pairs-in-an-array/
// @romitdutta10
// TC : O(n)
// Another Approach with two sets
classSolution {
publicintfindPairs(int[] nums, intk) {
if(nums == null || nums.length == 0) {
return0;
}
Set<String> pairs = newHashSet<>();
Set<Integer> visited = newHashSet<>();
for(intnum : nums) {
intgreater = num + k;
intlesser = num - k;
if(visited.contains(greater)) {
pairs.add(num + " " + greater);
}
if(visited.contains(lesser)) {
pairs.add(lesser + " " + num);
}
visited.add(num);
}
returnpairs.size();
}
}
// Problem : https://leetcode.com/problems/k-diff-pairs-in-an-array/