Fastest algorithm for circle shift N sized array for M position

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

    This method will do this work :

    public static int[] solution1(int[] A, int K) {
        int temp[] = new int[A.length];
    
        int count = 0;
    
        int orignalItration = (K < A.length) ? K :(K%A.length); 
    
    
        for (int i = orignalItration; i < A.length; i++) {
            temp[i] = A[count++];
        }
        for (int i = 0; i < orignalItration; i++) {
            temp[i] = A[count++];
        }
    
        return temp;
    }
    

提交回复
热议问题