问题 4:给定一个整数数组,将其转换为每个节点包含一个序列的链表。
Sample Input : [1, 3, 4, 5, 8, 9, 11, 13, 14, 15, 16, 20, 23, 30,31,32]
Sample Linked List : [1] -> [3,4,5] -> [8,9] -> [11] -> [13,14,15,16]->[20]->[23]->[30,31,32]
这个问题似乎很简单,但回答起来有点困难。任何人都可以在不使用Collection
or的情况下用 Java 编写上述代码LinkedList
吗?
下面是检测序列的代码(可能有帮助)。
class Sequence {
public static String detectSequence(int seq[]) {
String result = "";
for (int i = 0; i < seq.length - 1; i++) {
if (seq[i + 1] == seq[i] + 1) {
result += seq[i] + " ";
if (i != seq.length - 2) {
if (seq[i + 1] != seq[i + 2] - 1) {
result += seq[i + 1];
}
}
} else {
result += " ";
}
}
if (seq[seq.length - 1] == seq[seq.length - 2] + 1) {
result += seq[seq.length - 1];
}
return result;
}
}
class Question1 {
public static void main(String[] cla) {
int seqArray[] = {
4, 1, 2, 3, 4, 5, 8, 4, 7, 4, 5, 6, 7, 7, 7, 7, 7, 10, 11, 13, 1, 2, 3, 4
};
String res = Sequence.detectSequence(seqArray);
System.out.println(res);
}
}