我正在编写一个算法来打印数组中递增的序列,但我当前的解决方案并没有只打印最后一个序列。这是因为 if 条件不会在数组的最后一个索引处求值。下面的算法应该输出 [-10, 4] [1, 120, 150] [1, 5, 7]
但它会跳过 [1, 5, 7]
顺序。有人可以帮我吗!
public class Sequence {
public static void main(String[] args) {
int[] test = {1000, -10, 4, 1, 120, 150, 1, 5, 7};
Outputpattern(test);
}
public static void printList(int[] arr, int l, int u) {
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, l, u)));
}
public static void Outputpattern(int[] arr) {
int i = 0;
int l = 0;
while (i < arr.length - 1) {
if (arr[i] > arr[i + 1]) {
if (i != l) {
printList(arr, l, i + 1);
}
l = i + 1;
}
i++;
}
}
}
最佳答案
只有当你找到一个比前一个数字小的数字时,你才会打印一个序列。但是当你到达终点时,你还需要打印一个序列。如果序列的长度大于 1,此解决方案只会在最后打印序列。
int i = 0;
int l = 0;
while (i < arr.length) { // I changed the bound
if (i == arr.length - 1 || arr[i] > arr[i + 1]) { // I added a 2nd condition
if (i != l) {
printList(arr, l, i + 1);
}
l = i + 1;
}
i++;
}
关于java - 无法打印数组中的最后一个递增序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33026168/