|
| 1 | +package medium; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +public class _4SumII { |
| 8 | + |
| 9 | + /**Although it's tagged with BinarySearch and HashTable, I didn't come up with a good BinarySearch solution, then looked at this post: |
| 10 | + * https://discuss.leetcode.com/topic/67658/simple-java-solution-with-explanation*/ |
| 11 | + public static int fourSumCount(int[] A, int[] B, int[] C, int[] D) { |
| 12 | + Map<Integer, Integer> map = new HashMap(); |
| 13 | + int result = 0, len = A.length; |
| 14 | + for (int i = 0; i < len; i++){ |
| 15 | + for (int j = 0; j < len; j++){ |
| 16 | + int sum = A[i] + B[j]; |
| 17 | + if (map.containsKey(sum)){ |
| 18 | + map.put(sum, map.get(sum)+1); |
| 19 | + } else { |
| 20 | + map.put(sum, 1); |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + for (int i = 0; i < len; i++){ |
| 26 | + for (int j = 0; j < len; j++){ |
| 27 | + int sum = -(C[i] + D[j]); |
| 28 | + if(map.containsKey(sum)) result += map.get(sum); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return result; |
| 33 | + } |
| 34 | + |
| 35 | + public static void main(String...args){ |
| 36 | + int[] A = new int[]{1,2}; |
| 37 | + int[] B = new int[]{-2,-1}; |
| 38 | + int[] C = new int[]{-1,2}; |
| 39 | + int[] D = new int[]{0,2}; |
| 40 | + |
| 41 | + System.out.println(fourSumCount(A, B, C, D)); |
| 42 | + } |
| 43 | +} |
0 commit comments