java - 无法打印数组中的最后一个递增序列

标签 java arrays algorithm

我正在编写一个算法来打印数组中递增的序列,但我当前的解决方案并没有只打印最后一个序列。这是因为 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/

相关文章:

php - 汇总百分比所需的算法帮助

algorithm - 移除外部头引用后,ARC如何处理循环链表?

java - Json 对象针对给定键返回 null

java - 导入 MSN 联系人列表

java - 从服务访问 View

C# 从 byte[] 获取 string[]

java - 链接多个 Transformations.switchMap 关闭一个 LiveData 源

javascript - 根据不匹配某些值返回 JSON

python - 切片数组是否留下元组?需要使用数组切片作为整数,但 int() 不起作用

algorithm - 考虑到图像压缩,运行长度编码总是比霍夫曼编码好吗?