如何检查数字在链接列表中是否按顺序排列



我需要检查我存储在LinkedList中的数字是否按顺序排列。

示例集为:123、124、125、1900、1901。

如果代码遇到 123,它会检查下一个是 124 直到 125,然后停止,因为 1900 不是 125 之后的下一个数字,当你自然计数时。所以我需要获取第一个(123(和最后一个序列(125(的索引。然后进入下一个序列,1900年和1901年。

for(int o = 0; o < zeroIndex.size(); o++)
{
if(-1 == (zeroIndex.get(o) - zeroIndex.get(o+1)))
{
System.out.println(zeroIndex.get(o) + "trailing");
}
}
String serialIndex = "";
for(int o = 1; o < zeroIndex.size(); o++)
{serialIndex += "("+Integer.toString(o-1);
while(i<zeroIndex.size() && zeroIndex.get(o-1)+1 == zeroIndex.get(o))
{  i++;
//System.out.println(zeroIndex.get(o) + "trailing");
}
serialIndex = serialIndex+Integer.toString(i-1)+"),";
}
System.out.println(serialIndex);

我们将循环到链表,并检查前一个值是否比当前值小一。如果这个条件为真,我们将增加 i,否则我们将中断将循环并将 i 添加到 ans

例如


123、124、125、1900、1901。 我们将从
124 -----我们的serialIndex字符串将是 (0 和 124 比 123 大 1,所以我们递增 i.当我们达到 1900 时,我们将中断 while 循环,因为 1900 不是 1 大于 125,现在我们的 serialIndex 字符串将是 b(0,2(。
最后,我们将有串行索引字符串为 (0,2(,(3,4(


我没有你完整的代码来测试,所以这是我能做的最好的。如果您遇到任何错误,请告诉我。

这适用于 O(n(

import java.util.LinkedList;
public class TestLinkedList {
public static void main(String[] args) {
LinkedList<Integer> a = new LinkedList<Integer>();
a.add(124);
a.add(125);
a.add(126);
a.add(1900);
a.add(1901);
int index = 0;
int index1 = 0;
for (int i = 0; i < a.size(); i++) {
if (i+1 < a.size() && a.get(i) + 1 == a.get(i + 1)) {
index1 = i + 1;
} else {
if (index != index1) {
System.out.println(index + " " + index1);
}
index = i+1;
index1 = i+1;
}
}
}
}

输出

0 2
3 4

这是一个关于如何做到这一点的快速示例。首先,创建我们的列表。

List<Integer> a = new LinkedList<Integer>();
a.add(124);
a.add(125);
a.add(126);
a.add(1900);
a.add(1901);

所以,现在我们有一个列表,让我们开始吧。首先,声明我们的变量

int current; //will hold the current value during the iteration   
int indexStart = 0; //the index of the beginning of the current sequence
int previous = a.get(0); //the previous value
int length = a.size(); //the length (optionnal, but this will be used later)

然后,有趣的par来了(完全评论(

//Iterate from 1 to the end (0 is already in `previous`
for(int i = 1 ; i < length; ++i){
//get the current value
current = a.get(i); 
//if the sequence is broken, print the index and print also the sublist using `List.subList`.
if(current != previous + 1){ 
System.out.format("Sequence from %d to %d%n", indexStart, i - 1);
System.out.println(a.subList(indexStart, i));
//reset the start of the current sequence
indexStart = i; 
}
//update the previous value with the current for the next iteration.
previous = current;
}
//Print the last sequence.
System.out.format("Sequence from %d to %d%n", indexStart, length - 1);
System.out.println(a.subList(indexStart, length));

这将打印:

从0到2
的序列[124, 125, 126]从3到4
的序列[1900, 1901]

这很简单,只需迭代循环并保留先前和当前值即可检查序列是否正确。

请注意,对于LinkedList,我会使用Iterator但我需要一个int index,所以这将给出更长的解决方案,所以为了保持简单,我使用了List.get

最新更新