一尘不染

如何在整数数组中查找整数的重复序列?

algorithm

如何在整数数组中查找整数的重复序列?

00将重复,123123也将重复,但01234593623将不会重复。

我对如何执行此操作有一个想法,但是我的想法很模糊,因此我的实现并没有走多远。

我的主意是

  1. 每次经过for循环都会偏移一定量
  2. 在内部循环并通过该偏移量比较数字块

在Java中,我到此为止:

    String[] p1 = new String[nDigitGroup];
    String[] p2 = new String[nDigitGroup];

    for (int pos = 0; pos < number.length - 1; pos++)
    {
        System.out.println("HERE: " + pos + (nDigitGroup - 1));
        int arrayCounter = -1;

        for (int n = pos; n < pos + nDigitGroup ; n++)
        {
            System.out.printf("\nPOS: %d\nN: %d\n", pos, n);
            arrayCounter++;
            p1[arrayCounter] = number[n];

            System.out.println(p1[arrayCounter]);
        }

        pos += nDigitGroup;
        arrayCounter = -1;

        System.out.println("SWITCHING");

        for (int n = pos; n < pos + nDigitGroup ; n++)
        {
            System.out.printf("\nPOS: %d\nN: %d\n", pos, n);
            arrayCounter++;
            p2[arrayCounter] = number[n];

            System.out.println(p2[arrayCounter]);
        }

        if (p1[0].equals(p2[0]) && p1[1].equals(p2[1])) System.out.println("MATCHING");
    }

使用以下参数运行时:

        repeatingSeqOf(2, new String[] {"1", "2", "3", "4", "5", "6", "7", "7" });

我正确地填充了节数组,但是它在索引超出范围时中断。


阅读 234

收藏
2020-07-28

共1个答案

一尘不染

@MiljenMikic的答案很好,尤其是因为语法实际上不是常规的。:D

如果您想一般地在一个数组上进行操作,或者想了解它,那么可以做到正则表达式几乎完全可以做到:

public static void main(String[] args) {
    int[] arr = {0, 1, 2, 3, 2, 3}; // 2, 3 repeats at position 2.

    // for every position in the array:
    for (int startPos = 0; startPos < arr.length; startPos++) {
        // check if there is a repeating sequence here:

        // check every sequence length which is lower or equal to half the
        // remaining array length: (this is important, otherwise we'll go out of bounds)
        for (int sequenceLength = 1; sequenceLength <= (arr.length - startPos) / 2; sequenceLength++) {

            // check if the sequences of length sequenceLength which start
            // at startPos and (startPos + sequenceLength (the one
            // immediately following it)) are equal:
            boolean sequencesAreEqual = true;
            for (int i = 0; i < sequenceLength; i++) {
                if (arr[startPos + i] != arr[startPos + sequenceLength + i]) {
                    sequencesAreEqual = false;
                    break;
                }
            }
            if (sequencesAreEqual) {
                System.out.println("Found repeating sequence at pos " + startPos);
            }
        }
    }
}
2020-07-28