[
在第二个 for 循环中,如果 if 语句为 true,我需要保持 's' 的值相同。因此,我减小了 's' 的值,以便在下一步中增加它时,它保持不变。但这不起作用。为什么?
我给出两个数组,比如 3,2,1 和 1,2,3。我需要将第一个数组更改为第二个数组并计算所需的时间。我通过检查第一个元素来完成此操作。如果相同,则移至下一个,否则将第一个元素推到末尾,其余元素推到上面的一个位置并重复该过程。每次我将一个元素推到末尾时,我都会增加“时间”的值。
该代码在 [3,2,1] 和 [1,2,3] 上运行良好,但当涉及到图像中的示例时,它会继续运行。
import java.util.*;
public class Monkon {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number of test cases");
int t = Integer.parseInt(scn.nextLine());
int[][] p = new int[t][2];
int[] a = new int[t];
int[] b = new int[t];
int time = 0;
for (int s = 1; s <= t; s++) {
a[s - 1] = p[s - 1][0] = scn.nextInt();
b[s - 1] = p[s - 1][1] = scn.nextInt();
}
for (int s = 1; s <= t; s++) {
int c = a[s - 1];
if (b[s - 1] != a[s - 1]) {
for (int y = s; y < t; y++) {
a[y - 1] = a[y];
}
a[t - 1] = c;
time++;
s = s - 1;
} else
time++;
}
System.out.println(time);
}
}
最佳答案
您的代码的问题是,如果您无法通过您定义的操作将第一个数组转换为第二个数组,它将进入无限循环,这就是您面临的问题。
如果您考虑像 {3,2,1}
和 {1,2,3}
这样的示例,它会很好地终止并给出输出。
如果您给出像 {1,2,3}
和 {1,2,4}
这样的数组,它将进入无限循环,因为无法转换通过任意次数的操作将第一个数组转换为第二个数组。
我认为您也错误地读取了输入。我运行了你的程序,你可以看到截图here .
在输入{3,3,1,2,3,1,2}
中,第一个3
是元素数量的输入(您的测试用例中的程序术语)。
在剩余的输入中,替代数字将进入同一个数组,因为您正在读取输入,例如
a[s - 1] = p[s - 1][0] = scn.nextInt();
b[s - 1] = p[s - 1][1] = scn.nextInt();
在剩下的{3,1,2,3,1,2}中,粗体的数字将进入第一个数组 - {3,1,2}
,其他数字将进入第二个数组 - {1,3,2}
。
此输入给出 5
作为答案。
更新
为了简单起见,我建议您更换
for (int s = 1; s <= t; s++) {
a[s - 1] = p[s - 1][0] = scn.nextInt();
b[s - 1] = p[s - 1][1] = scn.nextInt();
}
与
for (int s = 1; s <= t; s++) {
a[s - 1] = p[s - 1][0] = scn.nextInt();
}
for (int s = 1; s <= t; s++) {
b[s - 1] = p[s - 1][1] = scn.nextInt();
}
关于java - 迭代后保持控制变量的值相同 - 为什么它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630772/