zoukankan      html  css  js  c++  java
  • java

    给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。

    为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。

    例如:

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

    输出:
    2

    解释:
    两个元组如下:
    1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
    2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/4sum-ii

    用暴力尝试时间复杂度O(n^4),超时。。。所以需要优化

    先把AB相加存入map,缩减合并同类项

    然后遍历C和D与map比较。

    时间复杂度理论上如果AB相加没有任何重复值的话其实一样。。。有重复值的话会缩减,但是空间复杂度上升。。。

    class Solution {
        public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
    
            int arrLength = A.length;
            int num = 0;
    
            HashMap<Integer, Integer> ab = new HashMap<Integer, Integer>();
    
            for(int i = 0; i < arrLength; i++){
                for(int j = 0; j < arrLength; j++) {
                    int result = A[i] + B[j];
                    if(ab.containsKey(result)){
                        ab.put(result,ab.get(result) + 1);
                    }
                    else{
                        ab.put(result, 1);
                    }
                }
            }
            for(int i = 0; i < arrLength; i++){
                for(int j = 0; j < arrLength; j++) {
                    int result = C[i] + D[j];
                    result = result * (-1);
                    if(ab.containsKey(result)){
                        num = num + ab.get(result);
                    }
                }
            }
    
            return num;
    
        }
    }
  • 相关阅读:
    JAVA 多线程(3)
    JAVA 多线程(2)
    JAVA 多线程(1):synchronized
    阿里金服设置公钥-验证私钥
    linux (1): 启动
    新建项目虚拟环境及pycharm配置
    python创建udp服务端和客户端
    python创建tcp服务端和客户端
    python并发(阻塞、非阻塞、epoll)
    mongo基本操作
  • 原文地址:https://www.cnblogs.com/clamp7724/p/12421667.html
Copyright © 2011-2022 走看看