|
| 1 | +// https://leetcode.com/problems/find-the-number-of-good-pairs-i |
| 2 | +// x = largest possible integer |
| 3 | +// T: O(n*sqrt(x) + m) |
| 4 | +// S: O(n + m) |
| 5 | + |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Map; |
| 8 | + |
| 9 | +public class FindTheNumberOfGoodPairsI { |
| 10 | + public int numberOfPairs(int[] array1, int[] array2, int k) { |
| 11 | + final Map<Integer, Integer> dividends = getDividendFrequencies(array1, k); |
| 12 | + final Map<Integer, Integer> divisors = getElementFrequencies(array2); |
| 13 | + int pairs = 0; |
| 14 | + |
| 15 | + for (Map.Entry<Integer, Integer> entry : dividends.entrySet()) { |
| 16 | + final int dividend = entry.getKey(); |
| 17 | + final int frequency = entry.getValue(); |
| 18 | + |
| 19 | + for (int i = 1 ; i * i <= dividend ; i++) { |
| 20 | + if (dividend % i == 0) { |
| 21 | + pairs += frequency * divisors.getOrDefault(i, 0); |
| 22 | + if (i != dividend / i) { |
| 23 | + pairs += frequency * divisors.getOrDefault(dividend / i, 0); |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return pairs; |
| 30 | + } |
| 31 | + |
| 32 | + private static Map<Integer, Integer> getElementFrequencies(int[] array) { |
| 33 | + final Map<Integer, Integer> frequencies = new HashMap<>(); |
| 34 | + for (int element : array) { |
| 35 | + frequencies.put(element, frequencies.getOrDefault(element, 0) + 1); |
| 36 | + } |
| 37 | + return frequencies; |
| 38 | + } |
| 39 | + |
| 40 | + private static Map<Integer, Integer> getDividendFrequencies(int[] array, int k) { |
| 41 | + final Map<Integer, Integer> frequencies = new HashMap<>(); |
| 42 | + for (int element : array) { |
| 43 | + if (element % k == 0) { |
| 44 | + int quotient = element / k; |
| 45 | + frequencies.put(quotient, frequencies.getOrDefault(quotient, 0) + 1); |
| 46 | + } |
| 47 | + } |
| 48 | + return frequencies; |
| 49 | + } |
| 50 | +} |
0 commit comments