Java中复制数组的不同方法
我正在通过我的学校提供的练习来解决这个问题。好吧,我几周前毕业了,在跳上 leetcode 之前正在浏览这个网站。
无论如何,这种方法swapAll使作为参数传递的两个数组相互复制。
对于那些无法查看问题的人,
编写一个名为的方法
swapAll,它接受两个整数数组作为参数并交换它们的全部内容。您可以假设传递的数组不为空且长度相同。例如,如果传递以下数组:
int[] a1 = {11, 42, -5, 27, 0, 89}; int[] a2 = {10, 20, 30, 40, 50, 60}; swapAll(a1, a2); After the call, the arrays should store the following elements: ```java a1: {10, 20, 30, 40, 50, 60} a2: {11, 42, -5, 27, 0, 89}
我实际上找到了两个解决此问题的方法
public static void swapAll(int[] a, int[] b) {
int[] c = new int[a.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
a[i] = b[i];
b[i] = c[i];
}
}
和
public static void swapAll(int[] a, int[] b) {
int[] c = new int[a.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, a, 0, a.length);
System.arraycopy(c, 0, b, 0, a.length);
}
但我想知道是否一种方法在运行时/内存方面具有优势
回答
我更喜欢另一种选择。一种不涉及创建整个不必要的临时数组的方法。基本上,第一种方法但使用单个临时int而不是数组。就像是,
public static void swapAll(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) {
int t = a[i];
a[i] = b[i];
b[i] = t;
}
}