gpt4 book ai didi

java - 检查一个数组是否与java中的另一个数组相反

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

我正在尝试创建一个方法,该方法将 2 int 数组作为输入参数,如果数组是反向的则返回 true,否则返回 false。这是我目前所知道的,但这是错误的。

public static void main(String[] args)
{
int b,a;
int[] data1 = {14,-70,-18,88,85,97,-65,13,-71,-12};
int[] data2 = {-12,-71,13,-65,97,85,88,-18,-70,14};
boolean check = true;

for (a=0;a<data1.length;a++)
{
for (b=data2.length-1;b>=0;b=b-1)
{
if (data1[a] != data2[b])
check=false
}
}
System.out.println(check);
}

我的示例假设打印 true 但它没有。我假设 2 个数组的长度相同。谁能帮忙?

最佳答案

您不需要两个循环 - 您只需要循环一次,在一个数组中“正常”使用索引,并从另一端使用另一个数组:

public static boolean checkReversed(int[] x, int[] y)
{
// For production code, possibly add nullity checks here (see comments)
if (x.length != y.length)
{
return false;
}
// Loop through x forwards and y backwards
for (int i = 0; i < x.length; i++)
{
if (x[i] != y[y.length - 1 - i])
{
// As soon as we've found a "mistake" we can exit:
// This is simpler (IMO) than keeping a "check" variable
return false;
}
}
return true;
}

关于java - 检查一个数组是否与java中的另一个数组相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2384829/

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