简体   繁体   English

如何检查数组是否在Java中增加数字序列?

[英]How to check if an array is increasing sequence of numbers in java?

I am trying to check if an array has increasing sequences of numbers from 1 to n using a method in java and want to solve the problem using array.我正在尝试使用 java 中的方法检查数组是否具有从 1 到 n 递增的数字序列,并希望使用数组解决问题。 I have this code我有这个代码

public static int isIncreasingSequence(int[] a) {
        int start = 1, startIndex = 0, endIndex = 0;

    if(a[0] != 1)   return 0;

    while (start < a.length) {
        for (int j = startIndex; j < endIndex; j++) {
            if(a[j] != j)   return 0;
        }

        startIndex += start;
        endIndex += startIndex;
        start++;
    }

    return 1;
}

The method should return 1 if the array is in the sequence 1, 1, 2, 1, 2, 3, 1, 2, 3, 4 and so on.如果数组的序列为 1、1、2、1、2、3、1、2、3、4 等,则该方法应返回 1。 I can't get the desired output with my test array.我的测试数组无法获得所需的输出。 Can anyone help me with it?任何人都可以帮助我吗?

You were close, you just have to be careful about where you place your increments.你很接近,你只需要小心你放置增量的位置。

Naively, you need to increment to sub-sequence each time while keeping track of the absolute index in the array.天真地,您需要每次递增到子序列,同时跟踪数组中的绝对索引。 Something like:就像是:

How does end keep track of the current sequence? end如何跟踪当前序列?

Because we iterate from 1 to end over and over again, and increment it by 1 until we reach the end of the array.因为我们从 1 开始一遍又一遍地迭代end ,然后将其递增 1,直到到达数组的末尾。 We are also incrementing the index of the array while we do this.在执行此操作时,我们也在增加数组的索引。

At first, end = 1. So, we iterate from 1 to 1, and check each index in the array making sure a[0] == 1.首先,end = 1。因此,我们从 1 到 1 进行迭代,并检查数组中的每个索引以确保 a[0] == 1。

Next, end = 2. So, we iterate from 1 to 2, and check each index in the array making sure a[1] == 1, a[2] == 2.接下来,end = 2。所以,我们从 1 到 2 迭代,并检查数组中的每个索引,确保 a[1] == 1, a[2] == 2。

Next, end = 3. So, we iterate from 1 to 3, and check each index in the array making sure a[3] == 1, a[4] == 2, a[5] == 3.接下来,end = 3。因此,我们从 1 到 3 迭代,并检查数组中的每个索引,确保 a[3] == 1、a[4] == 2、a[5] == 3。

And so on.等等。

public static int isIncreasingSequence(int[] a) {

        int end = 1; // Track the end of the current sequence
        int index = 0; // Track the index of the array

        while (index < a.length) {

            // Iterate througha larger and larger subsequence
            for (int i = 1; i <= end; i++) {
                if (a[index] != i) return 0;

                index++;
                if (index == a.length) break;
            }

            end++;
        }

        return 1;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM