|
| 1 | +package pp.arithmetic.leetcode; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by wangpeng on 2019-04-10. |
| 7 | + * 454. 四数相加 II |
| 8 | + * <p> |
| 9 | + * 给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。 |
| 10 | + * <p> |
| 11 | + * 为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。 |
| 12 | + * <p> |
| 13 | + * 例如: |
| 14 | + * <p> |
| 15 | + * 输入: |
| 16 | + * A = [ 1, 2] |
| 17 | + * B = [-2,-1] |
| 18 | + * C = [-1, 2] |
| 19 | + * D = [ 0, 2] |
| 20 | + * <p> |
| 21 | + * 输出: |
| 22 | + * 2 |
| 23 | + * <p> |
| 24 | + * 解释: |
| 25 | + * 两个元组如下: |
| 26 | + * 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 |
| 27 | + * 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 |
| 28 | + * |
| 29 | + * @see <a href="https://leetcode-cn.com/problems/4sum-ii/">4sum-ii</a> |
| 30 | + */ |
| 31 | +public class _454_fourSumCount { |
| 32 | + public static void main(String[] args) { |
| 33 | + _454_fourSumCount fourSumCount = new _454_fourSumCount(); |
| 34 | + System.out.println(fourSumCount.fourSumCount( |
| 35 | + new int[]{-1, -1}, |
| 36 | + new int[]{-1, 1}, |
| 37 | + new int[]{-1, 1}, |
| 38 | + new int[]{-1, 1}) |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * 最直接的方案就是四次循环拿到满足条件的计数,不过这个通不过,时间复杂度在O(n^4) |
| 44 | + * 可行解题思路: |
| 45 | + * 看题目关联到哈希表,所以往那个方向考虑下 |
| 46 | + * 1、先将4个数组分层两组A+B,C+D |
| 47 | + * 2、定义个一个hash表,存储A+B所有的结果计数 |
| 48 | + * 3、在遍历C+D的时候,取反后,看hash表中是否存在计数 |
| 49 | + * |
| 50 | + * @param A |
| 51 | + * @param B |
| 52 | + * @param C |
| 53 | + * @param D |
| 54 | + * @return |
| 55 | + */ |
| 56 | + public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { |
| 57 | + int retCount = 0; |
| 58 | + HashMap<Integer, Integer> map = new HashMap<>(); |
| 59 | + for (int i = 0; i < A.length; i++) { |
| 60 | + for (int j = 0; j < B.length; j++) { |
| 61 | + int sumAB = A[i] + B[j]; |
| 62 | + map.put(sumAB, map.getOrDefault(sumAB, 0) + 1); |
| 63 | + } |
| 64 | + } |
| 65 | + for (int i = 0; i < C.length; i++) { |
| 66 | + for (int j = 0; j < D.length; j++) { |
| 67 | + int sumCD = C[i] + D[j]; |
| 68 | + retCount += map.getOrDefault(-sumCD, 0); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return retCount; |
| 73 | + } |
| 74 | +} |
0 commit comments