您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

数组列表并找到具有相同编号的最长子序列

数组列表并找到具有相同编号的最长子序列

您可以使用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;
}
其他 2022/1/1 18:33:42 有464人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶