【发布时间】:2015-10-17 03:00:15
【问题描述】:
我已经有一个包含值的列表类型 Integer,如果一个元素范围的总和满足特定值,我想从索引零开始顺序测试,然后将此范围复制到列表中并将其存储在链接列表中.然后再次按顺序测试,但现在从上一个范围的下一个索引开始,所以如果上一个范围是索引 0 到索引 9,那么从索引 10 开始,重复该过程直到最后一个索引。
List<Integer> arrayB = new LinkedList<Integer>(); //this is the array with values in it
List<LinkedList> p = new LinkedList<LinkedList>();// this is the array of arrays
List<Integer> arrayA = new LinkedList<Integer>();// this is the range or the sub list of arrayB
public void function(int n)// suppose that n = 6 and arrayB have these value {1,2,3,1,1,1,1,2}
{
int count = 0;
for (int w : arrayB)
{
count = w + count;
arrayA.add(w);
if(count == n)
{
count = 0;
p.add((LinkedList) arrayA);
arrayA.clear();
}
}
}
但是,当我在 arrayA 中调用 clear 方法时,此代码会失败,因此无论使用何种数据结构,是否有任何替代代码可以使用此逻辑?
【问题讨论】:
-
这是一个非常长的第一句话。你在“如果一个范围的总和......”失去了我们。
-
你更早失去了我。关于何时开始调用
LinkedList和数组数组。在 Java 中,数组具有与列表不同的类型。如果您将“列表”称为“数组”,反之亦然,结果将是我们找出“数组”是指 Java 数组还是 JavaList。 -
@ergonaut 我已经编辑了帖子,如果您看到代码,它是一个元素范围的总和,例如 arrayB 中的元素具有元素 {1,2,3,1,1,1 ,1,2} 所以前 3 个元素的总和是 6,满足条件(count == n),所以范围是索引 0 到索引 2。
-
@StephenC 我已经根据通用集合而不是数组编辑了这个问题,但是这个问题并不限制在任何替代代码中使用数组来回答
-
“元素范围”是什么意思?数学意义上的范围?子列表?还有什么?
标签: java arrays data-structures linked-list