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

ArrayList生成全子数组代码异常:输出与预期不符求修正

问题分析与代码修正

你的代码出现错误的核心原因:所有存入ans的都是同一个temp对象的引用。在j的循环中,你持续向temp添加元素,而ans里存储的始终是指向这个temp的指针,因此最终所有子数组都会变成temp的最终状态(即从i起始到数组末尾的完整子数组)。

修正方案(推荐高效版本)

每次向ans中添加子数组时,创建一个新的ArrayList,复制当前temp的内容,确保每个子数组都是独立的对象:

public ArrayList<ArrayList<Integer>> solve(ArrayList<Integer> A) {
    int n = A.size();
    ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        ArrayList<Integer> temp = new ArrayList<>();
        for (int j = i; j < n; j++) {
            temp.add(A.get(j));
            // 添加temp的副本,而非原引用
            ans.add(new ArrayList<>(temp));
        }
    }
    return ans;
}

另一种实现思路(直观但效率稍低)

在j循环内部每次新建temp,从i到j逐个添加元素构建子数组:

public ArrayList<ArrayList<Integer>> solve(ArrayList<Integer> A) {
    int n = A.size();
    ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            ArrayList<Integer> temp = new ArrayList<>();
            for (int k = i; k <= j; k++) {
                temp.add(A.get(k));
            }
            ans.add(temp);
        }
    }
    return ans;
}

方案对比

  • 第一种方案时间复杂度为O(n²),仅在每次添加时复制当前temp的元素,效率更高。
  • 第二种方案时间复杂度为O(n³),需要重复遍历i到j的元素,适合理解逻辑但性能较差。

内容的提问来源于stack exchange,提问作者Shubham Kumar Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:02:46