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

Java使用多维ArrayList实现ArrayList子列表反转的代码问题排查

问题定位

你的代码存在三个核心错误:

    1. operations构造逻辑错误:你预期的操作列表是[[0,1], [1,3]],但实际运行时构造出来的是[[1], [3], []],完全不符合输入要求。你错误地用外层列表的索引作为反转起始位置,且没有给每个操作子列表填入正确的起始、结束两个索引值。
    1. 反转逻辑边界计算错误:你计算右边界时额外减了1,导致每次反转都会漏掉结束索引位置的元素。如果操作给出的区间是左闭右闭的[start, end],反转时的右边界直接用end即可。
    1. 操作遍历逻辑错误:你用了两层循环遍历operations,但operations的每个子元素本身就是一组完整的[start, end]操作参数,不需要嵌套循环遍历子列表的每个元素,直接取每组操作的第0位作为起始索引、第1位作为结束索引即可。

修正后的可运行代码

import java.util.*;
public class ReverseParameters {
   public static void main(String[] args) {
       List<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 2, 1, 3));
       List<List<Integer>> operations = new ArrayList<>();
       // 正确构造操作列表 [[0,1], [1,3]]
       operations.add(Arrays.asList(0,1));
       operations.add(Arrays.asList(1,3));

       subList(list, operations);
   }
   public static void subList (List<Integer> list, List<List<Integer>> operations) {
       System.out.println("初始列表:" + list);
       // 遍历每组反转操作
       for (List<Integer> op : operations) {
           int startInd = op.get(0);
           int endInd = op.get(1);
           // 边界校验,避免索引越界
           if (startInd < 0 || endInd >= list.size() || startInd >= endInd) {
               continue;
           }
           int left = startInd;
           int right = endInd;
           while (left < right) {
               int temp = list.get(left);
               list.set(left, list.get(right));
               list.set(right, temp);
               left++;
               right--;
           }
           System.out.printf("执行反转[%d,%d]后:%s%n", startInd, endInd, list);
       }
       System.out.println("最终列表:" + list);
   }
}

运行结果

初始列表:[5, 3, 2, 1, 3]
执行反转[0,1]后:[3, 5, 2, 1, 3]
执行反转[1,3]后:[3, 1, 2, 5, 3]
最终列表:[3, 1, 2, 5, 3]

与预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:15:07