Fastest algorithm for circle shift N sized array for M position

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

    static int [] shift(int arr[], int index, int k, int rem)
    {
        if(k <= 0 || arr == null || arr.length == 0 || rem == 0 || index >= arr.length)
        {
            return arr;
        }
    
        int temp = arr[index];
    
        arr = shift(arr, (index+k) % arr.length, k, rem - 1);
    
        arr[(index+k) % arr.length] = temp;
    
        return arr;
    }
    

提交回复
热议问题