Fastest algorithm for circle shift N sized array for M position

后端 未结 24 3054
温柔的废话
温柔的废话 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 05:40

    Here is my solution in Java which got me 100% Task Score and 100% Correctness at Codility:

    class Solution {
        public int[] solution(int[] A, int K) {
            // write your code in Java SE 8
            if (A.length > 0)
            {
                int[] arr = new int[A.length];
                if (K > A.length)
                    K = K % A.length;
    
                for (int i=0; i

    Note that despite seeing two for loops, the iteration on the entire array is only done once.

提交回复
热议问题