2006. Count Number of Pairs With Absolute Difference K
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public int countKDifference(int[] nums, int k) {
int n = nums.length, count = 0;
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
if(Math.abs(nums[i]-nums[j]) == k) {
count++;
}
}
}
return count;
}
}/**
* Time complexity :
* Space complexity :
*/
class Solution {
public int countKDifference(int[] nums, int k) {
if(nums == null || nums.length < 1) {
return 0;
}
int[] counter = new int[101];
for(int num: nums) {
counter[num]++;
}
int count = 0;
for(int i = k+1; i < counter.length; i++) {
count += (counter[i-k] * counter[i]);
}
return count;
}
}