java - 在 Java 中使用多维 ArrayList 反转 ArrayList 的子集
问题描述
我正在尝试使用多维列表中提供的索引来反转列表中的子列表。我没有太多使用多维列表/数组的经验。我不明白为什么这不起作用。
/*
Given a List<Integer> list and List<List<Integer>> operations
reverse the sublist and print out the list after all the operations have been done.
Ex: [5, 3, 2, 1, 3]
[[0,1], [1, 3]]
*/
import java.util.*;
public class ReverseParameters {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 3, 2, 1, 3);
List<List<Integer>> operations = new ArrayList<>(2);
for(int i= 0; i < 3; i++){
operations.add(new ArrayList<>());
}
operations.get(0).add(1);
operations.get(1).add(3);
subList(list, operations);
}
public static void subList (List<Integer> list, List<List<Integer>> operations) {
System.out.println(list);
int vertCount = operations.size();
for (int i = 0; i < vertCount; i++) {
int edgeCount = operations.get(i).size();
for (int j = 0; j < edgeCount; j++) {
int startInd = i;
int endInd = operations.get(i).get(j);
int shift = endInd - startInd;
int right = Math.min(i + shift - 1, list.size() - 1);
int temp = 0;
while (startInd < right) {
temp = list.get(startInd);
list.set(startInd, list.get(right));
list.set(right, temp);
startInd+=1;
right-=1;
}
System.out.println();
System.out.printf(" %d %d%n", startInd, endInd);
System.out.println();
}
}
System.out.println(list);
}
}
使用 [[0,1], [1, 3]] 作为指数的这段代码的输出是:
[5, 2, 3, 1, 3]
但应该是:
[3, 1, 2, 5, 3]
有人可以帮我指出正确的方向吗?
解决方案
您使用不必要的变量使代码过于复杂,从而难以找到问题。请查看更简单的代码和解释:
public static void main(String[] args) {
List<Integer> list = Arrays.asList(5, 3, 2, 1, 3);
List<List<Integer>> operations = new ArrayList<>(2);
// Initialize your operations
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) {
// You just iterate over the operations
for (List<Integer> operation : operations) {
// For each operation, store left and right indexes.
int left = operation.get(0);
int right = operation.get(1);
// Iterate until both indexes find each other
while (left < right) {
// Swap left and right elements in input list
int aux = list.get(left);
list.set(left, list.get(right));
list.set(right, aux);
// Now you move your indexes
++left;
--right;
}
}
System.out.println(list);
}
请注意,根据问题的要求,您可能还需要验证操作索引是否在列表边界内,这样您最终不会收到 ArrayIndexOutOfBoundsException。因此,请始终小心边缘情况。
推荐阅读
- spring - 从 yml 文件中读取数据的服务类
- python - 动态添加属性会创建不需要的别名
- java - 为什么 Flux.zip 接受预定义函数而不接受匿名函数?
- docker - 无法在 docker 容器中运行 jupyterhub
- python - 在 Pandas 中将字符串转换为时间
- python - 建议的最大任务大小为 100 KB 如何使用 python spark 解决此问题 如何在 python pyspark 中解决此问题
- qt - 如何读取 main.qml 中的 listmodel 角色属性?
- excel - 如何从 MSHTML.IHTMLElementCollection 中选择特定表
- excel - Excel Pivottable 刷新(2010 与 2016) - 为什么在 2016 年不工作,但在 2010 年工作?
- sql - Postgresql 约束在时间戳之间没有重叠