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

时间:2015-03-04 05:20:08

标签: java arrays algorithm math

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

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

我知道如何做到这一点,但在我看来它很模糊,而且由于这个原因我的实施并不顺利。

我的想法是

  1. 每次通过for循环时偏移一定数量
  2. 在其中循环,并通过该偏移量比较数字块
  3. 在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" });
    

    我正确地填充了section数组,但它在一个索引超出范围的异常中断了。

4 个答案:

答案 0 :(得分:4)

@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);
            }
        }
    }
}

答案 1 :(得分:3)

您始终可以使用正则表达式来实现所需的结果。使用regex backreference并将其与贪心量词结合使用:

    void printRepeating(String arrayOfInt)
    {
        String regex = "(\\d+)\\1";
        Pattern patt = Pattern.compile(regex);
        Matcher matcher = patt.matcher(arrayOfInt);           
        while (matcher.find())                              
        {               
            System.out.println("Repeated substring: " + matcher.group(1));
        } 
    }          

答案 2 :(得分:1)

@AdrianLeonhard发布的答案非常有效。但如果我有一系列的 0,1,2,3,4,3,5,6,4,7,8,7,8 许多人可能想知道如何从阵列中获取所有重复的数字。

所以,我写了这个简单的逻辑,用他们的位置打印所有重复的数字

    int[] arr = {0, 1, 2, 3, 4, 3, 5, 6, 4, 7, 8, 7, 8};

    for(int i=0; i<arr.length;i++){
        for(int j=i+1; j<arr.length;j++){
            if(arr[i] == arr[j]){
                System.out.println("Number: "+arr[i]+" found repeating at position: "+i+" , repeated at position "+j);
            }
        }
    }

答案 3 :(得分:-1)

试试这个:

string lookIn = "99123998877665544123"; 
// above has length of 20 (in positions 0 through 19)
int patternLength = 3;
// want to search each triple of letters 0-2, 1-3, 2-4 ... 17-19
//   however since there must be 3 chars after the 3-char pattern
//   we only want to search the triples up to 14-16 (20 - 3*2)
for (int i=0; i <= lookIn.Length - patternLength * 2; i++) {
   string lookingFor = lookIn.Substring(i, patternLength);
   // start looking at the pos after the pattern
   int iFoundPos = lookIn.IndexOf(lookingFor, i + patternLength);
   if (iFoundPos > -1) {
      string msg = "Found pattern '" + lookingFor 
                 + "' at position " + i 
                 + " recurs at position " + iFoundPos;
   }
}
// of course, you will want to validate that patternLength is less than
//   or equal to half the length of lookIn.Length, etc.

编辑:改进并转换为javascript(来自C#... oops,抱歉...)

function testfn() {
   var lookIn = "99123998877665544123"; 
   // above has length of 20 (in positions 0 through 19)
   var patternLength_Min = 2;
   var patternLength_Max = 5;
   if (patternLength_Max > (lookIn.length / 2) 
                || patternLength_Max < patternLength_Min
                || patternLength_Min < 1) {
      alert('Invalid lengths.')
   }
   var msg = "";
   for (var pLen = patternLength_Min; pLen <= patternLength_Max; pLen++)  {
      for (var i = 0; i <= lookIn.length - pLen * 2; i++) {
         var lookingFor = lookIn.substring(i, i + pLen);
         // start looking at the pos after the pattern
         var iFoundPos = lookIn.indexOf(lookingFor, i + pLen);
         if (iFoundPos > -1) {
            msg = msg + "Found '" + lookingFor 
                       + "' at pos=" + i 
                       + " recurs at pos=" + iFoundPos + "\n";
            ;
         }
      }
   }
   alert(msg);
}

消息框显示以下内容:

Found '99' at pos=0 recurs at pos=5
Found '12' at pos=2 recurs at pos=17
Found '23' at pos=3 recurs at pos=18
Found '123' at pos=2 recurs at pos=17