如何将两个数组组合成一个,交替元素?

时间:2022-04-06 19:17:21

Suppose you have array arr[N] of increasing numbers. You have to divide it in two other (Left and Right):

假设你有一个增加数的数组arr[N]。你必须把它分成两部分(左和右):

L = {0, 2, 4, 6, 8, 10, ...}

R = {1, 3, 5, 7, 9, 11, ...}

The following algorithm does this:

下面的算法是这样做的:

for ( i = 0; i < (N / 2) ; i++ )
    {
        L[i] = arr[2 * i + 0];
        R[i] = arr[2 * i + 1];
    }

The question is: How to do the reverse algorithm?

问题是:如何做逆向算法?

So the output array will be:

那么输出数组将是:

arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...}

P.S. I've been thinking a lot about it but with no rezult :(

注:我一直在想这个问题,但毫无疑问

2 个解决方案

#1


10  

The easy solution is just to literally reverse your existing operation:

简单的解决方案就是彻底改变你现有的操作:

for (i = 0; i < (N / 2); i++)
{
    arr[2 * i + 0] = L[i];
    arr[2 * i + 1] = R[i];
}

#2


3  

Your original problem doesn't specify whether or not the original array is guaranteed to have an even number of elements.

您的原始问题没有指定原始数组是否保证有偶数个元素。

If this is not the case your solution nor

如果这不是你的解决方案

 for (i = 0; i < (N / 2); i++) {
     arr[2 * i + 0] = L[i];
     arr[2 * i + 1] = R[i]; }

are guaranteed to work.

保证工作。

The safest bet would be

最安全的办法是

LR = {L, R};

for (i=0; i < N; i++) {
    LR[i mod 2][i/2] = arr[i];
}

as is posted above.

正如上面发布的。

#1


10  

The easy solution is just to literally reverse your existing operation:

简单的解决方案就是彻底改变你现有的操作:

for (i = 0; i < (N / 2); i++)
{
    arr[2 * i + 0] = L[i];
    arr[2 * i + 1] = R[i];
}

#2


3  

Your original problem doesn't specify whether or not the original array is guaranteed to have an even number of elements.

您的原始问题没有指定原始数组是否保证有偶数个元素。

If this is not the case your solution nor

如果这不是你的解决方案

 for (i = 0; i < (N / 2); i++) {
     arr[2 * i + 0] = L[i];
     arr[2 * i + 1] = R[i]; }

are guaranteed to work.

保证工作。

The safest bet would be

最安全的办法是

LR = {L, R};

for (i=0; i < N; i++) {
    LR[i mod 2][i/2] = arr[i];
}

as is posted above.

正如上面发布的。