Fastest algorithm for circle shift N sized array for M position

后端 未结 24 2978
温柔的废话
温柔的废话 2020-11-28 05:33

What is the fastest algorithm for circle shifting array for M positions?
For example, [3 4 5 2 3 1 4] shift M = 2 positions should be [1 4 3 4 5 2 3

24条回答
  •  渐次进展
    2020-11-28 06:03

    Similar to @IsaacTurner and not that elegant due to unnecessary copying, but implementation is quite short.

    The idea - swap element A on index 0 with the element B which sits on destination of A. Now B is first. Swap it with the element C which sits on destination of B. Continue until the destination is not at 0.

    If the greatest common divisor is not 1 then you're not finished yet - you need to continue swapping, but now using index 1 at your starting and end point.

    Continue until your starting position is not the gcd.

    int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);
    
    public int[] solution(int[] A, int K)
    {
        for (var i = 0; i < gcd(A.Length, K); i++)
        {
            for (var j = i; j < A.Length - 1; j++)
            {
                var destIndex = ((j-i) * K + K + i) % A.Length;
                if (destIndex == i) break;
                var destValue = A[destIndex];
                A[destIndex] = A[i];
                A[i] = destValue;
            }
        }
    
        return A;
    }
    

提交回复
热议问题