• 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;
    
        }
    }
  • 相关阅读:
    在UNICODE编码格式下, CString 转换为 char* :
    inet_ntop(), inet_pton(), htonl(), ntohl()
    'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)'
    NMAKE:fatal error U1077.“...cl.exe” return code 0xc0000135
    拷贝(复制)构造函数和赋值函数
    GIS 地图中术语解释
    Linux 下防火墙端口设置
    LInux 下安装jdk
    ln 命令
    zip命令
  • 原文地址:https://www.cnblogs.com/clamp7724/p/12421667.html
Copyright © 2020-2023  润新知