Interleave array in constant space

后端 未结 6 1041
生来不讨喜
生来不讨喜 2020-12-05 14:53

I ran across the following sample job interview question. How can I solve it?

Suppose we have an array a1, a2,... , an, b1, b2, ..., bn.

The goal is to chan

6条回答
  •  广开言路
    2020-12-05 15:30

    It's called in-place in-shuffle problem. Here is its implementation in C++ based on here.

    void in_place_in_shuffle(int arr[], int length)
    {
        assert(arr && length>0 && !(length&1));
    
        // shuffle to {5, 0, 6, 1, 7, 2, 8, 3, 9, 4}
        int i,startPos=0;
        while(startPos3) i=i/3;
    
        return i;
    }
    

    Test:

    int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};  
    int length = sizeof(arr)/sizeof(int);
    in_place_in_shuffle(arr, length);
    

    After this, arr[] will be {0, 5, 1, 6, 2, 7, 3, 8, 4, 9}.

提交回复
热议问题