Fastest algorithm for circle shift N sized array for M position

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

    Keep two indexes to the array, one index starts from beginning of the array to the end of array. Another index starts from the Mth position from last and loops through the last M elements any number of times. Takes O(n) at all times. No extra space required.

    circleArray(Elements,M){
     int size=size-of(Elements);
    
     //first index
     int i1=0;
    
     assert(size>M)
    
     //second index starting from mth position from the last
     int i2=size-M;
    
     //until first index reaches the end
     while(i1

提交回复
热议问题