gpt4 book ai didi

java - 将数组与其镜像进行比较

转载 作者:行者123 更新时间:2023-12-02 11:12:24 24 4
gpt4 key购买 nike

好吧,我有一个方法,需要接受一个充满int的数组,然后对照它的镜像进行检查,看看它匹配的最大镜像是什么。例如我有数组 [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;
}

第三种方法在某个地方失败了(返回 1 而不是 2),我很困惑为什么我的循环没有返回我想要的内容。任何帮助将不胜感激。

最佳答案

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

问题是这样的:

int[] tempA = Arrays.copyOfRange(aFor, 0, groupSize);

您总是将 tempB 与 aFor 的第一个长度为 groupSize 的子数组进行比较。将该行更改为

int[] tempA = Arrays.copyOfRange(aFor, i, i + groupSize);

它应该可以工作。

编辑不断出现失败案例。似乎 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++;
}

这不是最有效的,但它可能是一个有趣的优化练习。一种起始方法是从 aFor.length 开始 groupSize 并递减。一旦分配了 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;
}

发生的情况是 Arrays.copyOfRange 用零填充了超出范围的数字。我还添加了之前提到的提前退出选项。可能还有更多可以进行的优化

关于java - 将数组与其镜像进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16670250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com