|
| 1 | +package com.cheehwatang.leetcode; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +// Time Complexity : O(n^2), |
| 7 | +// where 'n' is the length of 'arr'. |
| 8 | +// We traverse 'arr' in a nested for-loop, checking each triplet for each 'arr[i]'. |
| 9 | +// |
| 10 | +// Space Complexity : O(n^2), |
| 11 | +// where 'n' is the length of 'arr'. |
| 12 | +// For each 'arr[i]', there are 'n' number of possible differences to store in the HashTable. |
| 13 | + |
| 14 | +public class ThreeSumWithMultiplicity_HashTable { |
| 15 | + |
| 16 | + // Approach: |
| 17 | + // Using a HashTable to record "target - arr[k]" of the equation, then traverse both 'i' and 'j' to check if equal. |
| 18 | + // Note that we rearranged the equation as arr[i] + arr[j] == target - arr[k]. |
| 19 | + // Each loop recording the frequency of "target - arr[k]", add the frequency if equal. |
| 20 | + |
| 21 | + public int threeSumMulti(int[] arr, int target) { |
| 22 | + int n = arr.length; |
| 23 | + // Store the first value of 'arr[k]' which is arr[n - 1], starting from right to left each iteration. |
| 24 | + Map<Integer, Integer> map = new HashMap<>(); |
| 25 | + map.put(target - arr[n - 1], 1); |
| 26 | + long count = 0; |
| 27 | + for (int j = n - 2; j >= 0; j--) { |
| 28 | + // Add the frequency of "target - arr[k]" to the count if found. |
| 29 | + for (int i = j - 1; i >= 0; i--) { |
| 30 | + count += map.getOrDefault(arr[i] + arr[j], 0); |
| 31 | + } |
| 32 | + // Once done with all the 'j' for this loop, increase the frequency for "target - arr[j]". |
| 33 | + int difference = target - arr[j]; |
| 34 | + map.put(difference, map.getOrDefault(difference, 0) + 1); |
| 35 | + } |
| 36 | + return (int) (count % (1e9 + 7)); |
| 37 | + } |
| 38 | +} |
0 commit comments