LeetCode 454 4Sum II

题目

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.

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.

Example:

Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

Output:
2

Explanation:
The two tuples are:
(0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
(1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0


解法思路(一)

  • 用四重循环,做一个 O(N4) 的解法,在 5004 的数量级的情况下肯定是跑不完的;
  • N = 500 的话,用 O(N2) 的时间复杂度的解法去跑是可行的;
如何实现一个 O(N2) 的解法呢?
  • 如果把 C 和 D 两两组合之和存进一个 HashMap 中,key 是两两组合之和,value 是该和出现的次数,这个动作的时间复杂度是 O(N2);
  • 那么 A 和 B 的两两组合之和去这个 HashMap 中匹配,这个匹配的动作是 O(1) 的,而 A 和 B 的两两组合之和是 O(N2) 的,则总的时间复杂度是 O(2N2) = O(N2);

解法实现(一)

时间复杂度
  • O(N2);
空间复杂度
  • O(N2)
关键字

查找表 HashMap 二维将一维 O(N^2) 降 O(1)

package leetcode._454;

import java.util.HashMap;

public class Solution454_1 {

    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {

        HashMap<Integer, Integer> CDCombination = new HashMap<>(C.length * D.length);
        for (int i = 0; i < C.length; i++) {
            for (int j = 0; j < D.length; j++) {
                int CDAdd = C[i] + D[j];
                if (CDCombination.containsKey(CDAdd)) {
                    CDCombination.put(CDAdd, CDCombination.get(CDAdd) + 1);
                } else {
                    CDCombination.put(CDAdd, 1);
                }
            }
        }

        int combination = 0;
        for (int i = 0; i < A.length; i++) {
            for(int j = 0; j < B.length; j++) {
                int complement = 0 - A[i] - B[j];
                if (CDCombination.containsKey(complement)) {
                    combination += CDCombination.get(complement);
                }
            }
        }

        return combination;
    }

    public static void main(String[] args) {
        int[] A = {1, 2};
        int[] B = {-2, -1};
        int[] C = {-1, 2};
        int[] D = {0, 2};

        int result = (new Solution454_1()).fourSumCount(A, B, C, D);;
        System.out.println(result);
    }

}

返回 LeetCode [Java] 目录

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 专业考题类型管理运行工作负责人一般作业考题内容选项A选项B选项C选项D选项E选项F正确答案 变电单选GYSZ本规程...
    小白兔去钓鱼阅读 10,604评论 0 13
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 4,062评论 0 2
  • 1. 关于诊断X线机准直器的作用,错误的是()。 (6.0 分) A. 显示照射野 B. 显示中心线 C. 屏蔽多...
    我们村我最帅阅读 11,452评论 0 5
  • Description Given four lists A, B, C, D of integer values...
    Nancyberry阅读 179评论 0 0
  • 问题: Given four lists A, B, C, D of integer values, comput...
    Cloudox_阅读 151评论 0 0

友情链接更多精彩内容