栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以使用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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/515743.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号