You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode 18. 4Sum代码错误排查:特定测试用例输出异常

4Sum问题整数溢出错误排查

错误根源

你的代码在处理超大整数时发生整数溢出,导致逻辑判断错误:

  • 输入元素1000000000的四次求和数学值为4000000000,远超Java int类型的最大值2147483647。
  • 当用int存储四个数的和时,会溢出为-294967296(正好等于给定的target),让代码错误判定该四元组符合条件。
  • 代码中所有涉及多元素求和的逻辑都依赖int类型,无法正确处理超大数值的计算。

修复方案

将所有涉及求和的中间变量改为long类型,从根源避免溢出:

  1. 计算nums[i] + nums[j]时,先转为long再执行加法。
  2. 存储目标剩余值tsum时使用long类型。
  3. 比较nums[low] + nums[high]与tsum时,同样用long计算当前和。

修复后的代码

import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        int n = nums.length;

        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < n - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int low = j + 1;
                int high = n - 1;
                // 用long存储目标剩余值,避免溢出
                long tsum = (long) target - (long) nums[i] - (long) nums[j];
                while (low < high) {
                    // 计算当前两数和时转为long
                    long currentSum = (long) nums[low] + (long) nums[high];
                    if (tsum == currentSum) {
                        ans.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high]));
                        // 去重逻辑保持不变
                        while (low < high && nums[low] == nums[low + 1]) {
                            low++;
                        }
                        while (low < high && nums[high] == nums[high - 1]) {
                            high--;
                        }
                        low++;
                        high--;
                    } else if (tsum > currentSum) {
                        low++;
                    } else {
                        high--;
                    }
                }
            }
        }
        return ans;
    }
}

内容的提问来源于stack exchange,提问作者Rahul_0_67887

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 09:27:01