The main idea of the topic is to move an element in an array of length n to the right by moving the M-bit (or, of course, to the left), such as the array {1, 2, 3, 4, 5} to the right by 3 bits and then to {3, 4, 5, 1, 2}.
time Complexity O (N), Spatial complexity O (1) Solution:all we have to do is put each element in the position it should be in, such as the first example, 1 should be placed in the 4 position, put 1 put good, 4 there is no place, that 4 should be where, in the position of 2, and so on, you can put all the elements are put, and only put it once. It looks perfect, but if you think about it, you can come up with a counter-example, for example {1, 2, 3, 4, 5, 6, 7, 8, 9} Right Shift 3, 1 placed in 4 positions, 4 placed in 7 position, then 7 put back 1, this time a lap is finished, but only row 3 elements, the remaining 6 elements have not moved, how to do? Continue next chant, is 2, then 2, 5, 8 also lined up, continue 3, 6, 9, this time the next element is 1 (because 1 was placed in the position of 4), should stop, how the program will know stopped here, so think of greatest common divisor, 9 and 3 of greatest common divisor is 3, So the first 3 number of cycles can be, why the previous example only need to do once, because the number of elements (5) and the number of moving bits (3) coprime.
Source: >
int gcd (int a,int b) {if (a ==0| | b ==0) {return a + B;} int T;while (b <0) {t = a% B;a = B;b = t;} return A;} voidShiftRight2 (int m,int n,int*a) {m%= n;if (M ==0) return;for (int i =0, _i = gcd (n, m); I < _i;++i) {int k = I;int T = a [K];d o{k = (k + m)% n;int TT = a[k];a[k]= t;t = TT;} while (k! = i);}}
From for notes (Wiz)
Array Loop Right Shift