Loading
Leetcode / shuffle-the-array

Pick a programming language:

Here is the source code for the solution to this problem.

class Solution
{
    int[] shuffle(int[] nums, int n)
    {
        int[] arr = new int[2 * n];

        for (int k = 0, i = 0, j = n; k < 2 * n; k += 2, i++, j++)
        {
            arr[k] = nums[i];
            arr[k + 1] = nums[j];
        }

        return arr;
    }

    void test()
    {
        int[] testdata1 = {2, 5, 1, 3, 4, 7};
        shuffle(testdata1, 3);
        assert testdata1[0] == 2;
        assert testdata1[1] == 3;
        assert testdata1[2] == 5;
        assert testdata1[3] == 4;
        assert testdata1[4] == 1;
        assert testdata1[5] == 7;

        int[] testdata2 = {1, 2, 3, 4, 4, 3, 2, 1};
        shuffle(testdata2, 4);
        assert testdata2[0] == 1;
        assert testdata2[1] == 4;
        assert testdata2[2] == 2;
        assert testdata2[3] == 3;
        assert testdata2[4] == 3;
        assert testdata2[5] == 2;
        assert testdata2[6] == 4;
        assert testdata2[7] == 1;

        int[] testdata3 = {1, 1, 2, 2};
        shuffle(testdata3, 2);
        assert testdata3[0] == 1;
        assert testdata3[1] == 2;
        assert testdata3[2] == 1;
        assert testdata3[3] == 2;
    }

    public static void main(String[] args)
    {
        new Solution().test();
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: