您可以使用2D ArrayList,其声明如下:
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
然后在过程结束时声明要添加到其中的2个ArrayList:
ArrayList<Integer> length = new ArrayList<Integer>();
ArrayList<Integer> value = new ArrayList<Integer>();
然后
1)遍历列表,检查元素是否与先前相同。
如果是的话,请进行到最后,否则将发现一个不同的元素,此时在ArrayList中将先前相等元素的数量存储在“ length”中,并将元素的值存储在一个称为“ value”的中。有一个int(称为index),它存储元素的索引的长度,该长度包含当前最长子序列的长度(它将与包含其组成的元素的值的元素的索引相同(已存储在值中))。
如果不是,请移至下一个元素。
2)重复该过程,必要时更新索引(即,如果发现更长的子序列)。
要增加长度和值以得出最后的结果,只需执行result.add(length);
和result.add(value);
如果要返回一个包含所有必需信息的对象,则可以将int’index’包装在Integer中,并将其添加到名为’length’的ArrayList的末尾,甚至可以将其放入新的ArrayList中并添加该ArrayList导致。
请注意,要在结果存储到第一个ArrayList中的索引i处检索元素(在本例中为“ length”),您需要执行以下操作:
result.get(0).get(i);
编辑:
所以我想到的for循环部分是这样的:
boolean same = false;
int sequenceLength = 0;
Integer sequenceInteger = null;
for (int i = 1; i < numbers.size(); i++)
{
if(numbers.get(i).equals(numbers.get(i-1)))
{
same = true;
sequenceLength++;
}
else(if same == true)
{
sequenceInteger = new Integer(sequenceLength);
//add sequenceInteger to length and numbers.get(i-1) to value
same = false;
sequenceLength = 0;
}
// else do nothing since same is false, which means that the current
// element is different from the prevIoUs and the prevIoUs is
// different the one before that, so there are no new values to store
}
// end of list reached
(if same == true)
{
sequenceInteger = new Integer(sequenceLength);
//add sequenceInteger to length and numbers.get(i-1) to value
same = false;
}