|
| 1 | +package com.cheehwatang.leetcode; |
| 2 | + |
| 3 | +// Time Complexity : O(n + k), |
| 4 | +// where 'n' is the length of 'nums', and 'k' is 'k'. |
| 5 | +// We traverse 'nums' to count the numbers in 'nums', and we traverse maximum 'k' length to get the count. |
| 6 | +// |
| 7 | +// Space Complexity : O(1), |
| 8 | +// as the auxiliary space used is independent of the input. |
| 9 | + |
| 10 | +public class CountNumberOfPairsWithAbsoluteDifferenceK_Counting { |
| 11 | + |
| 12 | + // Approach: |
| 13 | + // Using a counting array to record the frequency of occurrence for all the numbers in 'nums'. |
| 14 | + // Since we know the number ranges from 1 to 100, we can build array of that size to keep track. |
| 15 | + |
| 16 | + public int countKDifference(int[] nums, int k) { |
| 17 | + |
| 18 | + // Counting array of size 101, since it is 0-indexed. |
| 19 | + int[] countingArray = new int[100 + 1]; |
| 20 | + |
| 21 | + // Record the frequency for all the numbers. |
| 22 | + for (int number : nums) countingArray[number]++; |
| 23 | + |
| 24 | + // The number of combinations is the multiples of both frequency. |
| 25 | + // e.g. [1,1,2,2,2] can have 2 * 3 = 6 combinations for k = 1. |
| 26 | + // Since we are traversing from 1 to 100, we will only add to the count if both i and i+k is > 0 frequency. |
| 27 | + // With that, we do not need to compare with i-k. |
| 28 | + int count = 0; |
| 29 | + for (int i = 1; i < countingArray.length - k; i++) { |
| 30 | + count += countingArray[i] * countingArray[i + k]; |
| 31 | + } |
| 32 | + return count; |
| 33 | + } |
| 34 | +} |
0 commit comments