IT干货网

arrays之面试题 : Replacing two arrays's place in memory

third_qq_acbf90bbd2dede1d 2024年11月01日 编程设计 90 0

给定两个连续的数组,AB .他们看起来像

int AandB[] = {a1,a2,...,am,b1,b2,...,bn}; 

您需要编写一个程序来切换数组的顺序 AB在内存中,这样 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--; 
    } 
} 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!