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:
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

===============================================================

Idea : The 'getOrDefault' method reduces the use of one 'get' method

===============================================================

Code : 

class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        Map<Integer,Integer> AB=new HashMap<Integer, Integer>();
        int length = A.length;
        for(int i=0;i<length;i++){
            for(int j=0;j<length;j++){
                int temp1=A[i]+B[j];
                AB.put(temp1,AB.getOrDefault(temp1,0)+1);
            }
        }
        int res=0;
        for(int i=0;i<length;i++)
            for(int j=0;j<length;j++)
                res+=AB.getOrDefault(-(C[i]+D[j]),0);
        return res;
    }
}

 

以下是对这段 Python 代码存在问题的分析: ### 1. 文件打开模式冲突 代码中先以写入模式 `"w"` 打开文件 `"in 162.txt"`,写入用户输入的内容后又以写入模式 `"w"` 打开该文件。以写入模式打开文件时,会清空文件原有的内容,所以后续的 `a.read()` 读取操作将得不到预期的结果,因为文件内容已被清空。应将第二次打开文件的模式改为读取模式 `"r"`。 ### 2. 变量重复使用 变量 `a` 被重复用于不同的文件操作,这样会造成混淆,不利于代码的理解和维护。建议使用不同的变量名来区分不同的文件对象。 ### 3. 变量 `sum` 的使用问题 在 Python 中,`sum` 是内置函数名,将其作为变量名使用会覆盖内置函数,可能导致后续使用 `sum` 函数时出现错误。建议使用其他变量名,如 `total`。 ### 4. 数据类型问题 `i` 是从文件读取的字符串,直接进行 `i * 0.454` 运算会引发类型错误,因为字符串不能直接与浮点数相乘。需要先将 `i` 转换为数值类型(如 `float` 或 `int`)。 ### 5. 文件打开位置问题 在循环中每次都以写入模式 `"w"` 打开文件 `"out 162.txt"`,这会导致每次循环时都会清空文件内容,最终文件中只会保留最后一次循环写入的内容。应将文件打开操作放在循环外部。 ### 修正后的代码 ```python # 以写入模式打开文件 "in 162.txt" file_write = open("in 162.txt", "w") # 获取用户输入 user_input = input() # 将用户输入写入文件 file_write.write(user_input) # 关闭写入文件 file_write.close() # 以读取模式打开文件 "in 162.txt" file_read = open("in 162.txt", "r") # 读取文件内容 content = file_read.read() # 关闭读取文件 file_read.close() # 分割文件内容为列表 words = content.split() # 以写入模式打开文件 "out 162.txt" output_file = open("out 162.txt", "w") # 初始化总和变量 total = 0 # 遍历列表中的每个元素 for word in words: try: # 将元素转换为浮点数 num = float(word) # 计算当前元素乘以 0.454 的结果 result = num * 0.454 # 累加结果到总和 total += result # 打印当前结果 print(result) except ValueError: print(f"无法将 {word} 转换为数字,跳过该元素。") # 关闭输出文件 output_file.close() # 打印最终总和 print("总和:", total) ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值