|
3 | 3 | import java.util.HashMap;
|
4 | 4 | import java.util.Map;
|
5 | 5 |
|
6 |
| -/**Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. |
7 |
| -
|
8 |
| - To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. |
| 6 | +/** |
| 7 | + * 454. 4Sum II |
| 8 | + * |
| 9 | + * Given four lists A, B, C, D of integer values, |
| 10 | + * compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. |
| 11 | + * To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. |
| 12 | + * All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. |
9 | 13 |
|
10 | 14 | Example:
|
11 | 15 |
|
|
25 | 29 |
|
26 | 30 | public class _454 {
|
27 | 31 |
|
28 |
| - public static int fourSumCount(int[] A, int[] B, int[] C, int[] D) { |
29 |
| - Map<Integer, Integer> map = new HashMap(); |
30 |
| - int result = 0; |
31 |
| - int len = A.length; |
32 |
| - for (int i = 0; i < len; i++) { |
33 |
| - for (int j = 0; j < len; j++) { |
34 |
| - int sum = A[i] + B[j]; |
35 |
| - if (map.containsKey(sum)) { |
36 |
| - map.put(sum, map.get(sum) + 1); |
37 |
| - } else { |
38 |
| - map.put(sum, 1); |
| 32 | + public static class Solution1 { |
| 33 | + public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { |
| 34 | + Map<Integer, Integer> map = new HashMap(); |
| 35 | + int result = 0; |
| 36 | + int len = A.length; |
| 37 | + for (int i = 0; i < len; i++) { |
| 38 | + for (int j = 0; j < len; j++) { |
| 39 | + int sum = A[i] + B[j]; |
| 40 | + if (map.containsKey(sum)) { |
| 41 | + map.put(sum, map.get(sum) + 1); |
| 42 | + } else { |
| 43 | + map.put(sum, 1); |
| 44 | + } |
39 | 45 | }
|
40 | 46 | }
|
41 |
| - } |
42 | 47 |
|
43 |
| - for (int i = 0; i < len; i++) { |
44 |
| - for (int j = 0; j < len; j++) { |
45 |
| - int sum = -(C[i] + D[j]); |
46 |
| - if (map.containsKey(sum)) { |
47 |
| - result += map.get(sum); |
| 48 | + for (int i = 0; i < len; i++) { |
| 49 | + for (int j = 0; j < len; j++) { |
| 50 | + int sum = -(C[i] + D[j]); |
| 51 | + if (map.containsKey(sum)) { |
| 52 | + result += map.get(sum); |
| 53 | + } |
48 | 54 | }
|
49 | 55 | }
|
50 |
| - } |
51 | 56 |
|
52 |
| - return result; |
| 57 | + return result; |
| 58 | + } |
53 | 59 | }
|
54 | 60 | }
|
0 commit comments