给定两个连续的数组,A
和 B
.他们看起来像
int AandB[] = {a1,a2,...,am,b1,b2,...,bn};
您需要编写一个程序来切换数组的顺序
A
和 B
在内存中,这样B
会出现在 A
之前.在我们的示例中,AandB
应该成为int AandB[] = {b1,b2,...,bn,a1,...,am};
最有效的方法是什么?
最佳答案
三个数组反转:
(a1 a2 a3 a4 a5 b1 b2 b3)
b3 b2 b1 a5 a4 a3 a2 a1
(b3 b2 b1)a5 a4 a3 a2 a1
b1 b2 b3 a5 a4 a3 a2 a1
b1 b2 b3(a5 a4 a3 a2 a1)
b1 b2 b3 a1 a2 a3 a4 a5
使用带有开始和结束的“rev”函数表示:
rev(AandB, 0, n+m)
rev(AandB, 0, m)
rev(AandB, m, n)
对于 rev(为了清楚起见,省略类型等):
rev(x, i, j) {
j--; // j points to one after the subarray we're reversing
while (i < j) {
tmp = x[i];
x[i] = x[j];
x[j] = tmp;
i++;
j--;
}
}
关于arrays - 面试题 : Replacing two arrays's place in memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4736112/