将数组与其镜像进行比较

Cav*_*n42 2 java arrays loops

好的,所以我有一个方法需要接受一个完整的数组ints,然后检查它的镜像,看看它匹配的最大镜像是什么.所以例如我有数组[7, 1, 2, 9, 7, 2, 1],它可以匹配的最大数组是2,匹配在[1, 2].

现在我将它分为3种方法.一个接受数组,另一个反转数组并返回它(mirrorArray).第三个是计算匹配(groupCount)的数组的大小.这是我到目前为止:

public int maxMirror(int[] nums) {
  int[] revArray = mirrorArray(nums);

  return groupCount(nums, revArray);
}

private int[] mirrorArray(int[] nums) {
  int[] newArray = new int[nums.length];

  for (int i = nums.length-1, j = 0; i >= 0; i--, j++) {
    newArray[j] = nums[i];
  }

  return newArray;
}

private int groupCount(int[] aFor, int[] bRev) {
  int maxCount = 0;
  int groupSize = 1;

  //get aFor value
  for (int i = 0; i < aFor.length; i++) {
    int[] tempA = Arrays.copyOfRange(aFor, 0, groupSize);

    //loop through bRev and check for matches
    for (int j = 0; j < bRev.length; j++) {
      int[] tempB = Arrays.copyOfRange(bRev, j, j+groupSize);

      if (Arrays.equals(tempA, tempB)) {
        maxCount = tempA.length;
      }
    }

    groupSize++;
  }
  return maxCount;
}
Run Code Online (Sandbox Code Playgroud)

它在某个地方的第3个方法失败了(返回1而不是2)并且我难以理解为什么循环我已经返回我想要的东西.任何帮助将不胜感激.

NG.*_*NG. 5

好吧,我很好奇......

这是问题所在:

int[] tempA = Arrays.copyOfRange(aFor, 0, groupSize);
Run Code Online (Sandbox Code Playgroud)

您始终将tempB与aFor长度的第一个subArray进行比较groupSize.将该行更改为

int[] tempA = Arrays.copyOfRange(aFor, i, i + groupSize);
Run Code Online (Sandbox Code Playgroud)

它应该工作.

编辑保持故障情况即将发生..似乎groupSize的增量位置存在问题

   while (groupSize < aFor.length) {
      //get aFor value
      for (int i = 0; i < aFor.length; i++) {
        int[] tempA = Arrays.copyOfRange(aFor, i, i + groupSize);

        //loop through bRev and check for matches
        for (int j = 0; j < bRev.length; j++) {
          int[] tempB = Arrays.copyOfRange(bRev, j, j+groupSize);

          if (Arrays.equals(tempA, tempB)) {
            maxCount = groupSize;
          }
        }
      }
      groupSize++;
  }
Run Code Online (Sandbox Code Playgroud)

这不是最有效的,它可能是一个有趣的优化练习.一种开始的方法是启动groupSize aFor.length和减少.一旦maxCount分配,您可以尽早返回.

编辑2

 int groupSize = aFor.length;
 while (groupSize >= 0) {
      //get aFor value
      for (int i = 0; i <= aFor.length - groupSize; i++) { // note this change
        int[] tempA = Arrays.copyOfRange(aFor, i, i + groupSize);

        //loop through bRev and check for matches
        for (int j = 0; j <= bRev.length - groupSize; j++) { // note this change
          int[] tempB = Arrays.copyOfRange(bRev, j, j+groupSize);

          if (Arrays.equals(tempA, tempB)) {
            return groupSize;
          }
        }
      }
      groupSize--;
  }
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

发生的事情是Arrays.copyOfRange用零填充了边界数字.我还添加了前面提到的早期退出选项.可能有更多优化可以完成