Diz*_*Diz 1 java arrays methods reverse
我正在尝试创建一个接收数组然后以相反方式返回该数组的方法.我写的代码反过来返回数组,但是,前两个值现在为0.任何人都知道我做错了什么?
public static int[] reverse(int[] x)
{
int []d = new int[x.length];
for (int i = 0; i < x.length/2; i++) // for loop, that checks each array slot
{
d[i] = x[i];
x[i] = x[x.length-1-i]; // creates a new array that is in reverse order of the original
x[x.length-1-i] = d[i];
}
return d; // returns the new reversed array
}
Run Code Online (Sandbox Code Playgroud)
您正在将未初始化数组中的值分配d给x- 这是零(intJava中的默认值)来自的位置.
IIUC,你正在混合两种逆转策略.
如果您正在创建一个新数组,则无需运行原始数组的一半以上,而是覆盖所有数组:
public static int[] reverse(int[] x) {
int[] d = new int[x.length];
for (int i = 0; i < x.length; i++) {
d[i] = x[x.length - 1 -i];
}
return d;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果你想在适当的位置反转数组,你不需要一个临时数组,只需要一个变量(最多 - 还有一些方法可以int在没有附加变量的情况下切换两个变量,但这是一个不同的问题):
public static int[] reverseInPlace(int[] x) {
int tmp;
for (int i = 0; i < x.length / 2; i++) {
tmp = x[i];
x[i] = x[x.length - 1 - i];
x[x.length - 1 - i] = tmp;
}
return x; // for completeness, not really necessary.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16648 次 |
| 最近记录: |