Fastest algorithm for circle shift N sized array for M position

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

    A very simple solution. This is a very fast way, here I use a temp array with the same size or original and attach to the original variable at the end. This method use O(n) temporal complexity and O(n) space complexity and it is very simple to implement.

    int[] a  = {1,2,3,4,5,6};
        int k = 2;
        int[] queries = {2,3};
    
        int[] temp = new int[a.length];
        for (int i = 0; i

提交回复
热议问题