Given an integer array nums
and an integer k
, return the number of pairs (i, j)
where i < j
such that |nums[i] - nums[j]| == k
.
The value of |x|
is defined as:
x
ifx >= 0
.-x
ifx < 0
.
LeetCode Problem - 2006
class Solution {
// Function to count pairs in the array with a difference of k
public int countKDifference(int[] nums, int k) {
int count = 0; // Initialize count of pairs
for(int i=0; i<nums.length; i++){ // Loop through the array
for(int j=i+1; j<nums.length; j++){ // Iterate over elements ahead of the current element
int flag = Math.abs(nums[i] - nums[j]); // Calculate the absolute difference between the elements
if(flag == k) count++; // If the absolute difference equals k, increment count
}
}
return count; // Return the count of pairs with a difference of k
}
}