1<=n<=), M (m>=0); line 2nd enter N integers, separated by a space. output format: The sequence of integers after the output loop is shifted to the right of the M-bit in a row, separated by a space, with no extra spaces at the end of the sequence. Input Sample: 6 2 1 2 3 4 5 6 Output Sample :561234
It is not easy to make a good algorithm because the new array is not required.
Loop right Shift N elements, then minimum complexity should be able to do O (N)
Then the greatest common divisor of M and n can be calculated first GCD
The number of GCD, the moving element, is the number of circle. According to the above example, 6,2 's GCD is 2, the elements in the array are actually divided into two groups to move, 1,3,5 a group, 2,4,6 a group
We can follow this method to design the method of moving.
Finally written out of the program, Time O (N), Space O (1), each CIRCLR only need to move n/gcd+1 secondary elements. The number of moves is probably lower than this.
Paste Code
#include <stdio.h>#include<stdlib.h>intn,m,*A;intgcdintAintb) { if(a%b==0){ returnb; } returnGCD (b,a-a/b*b);}intMainvoid) {scanf ("%d%d",&n,&m); M=m%N; A=(int*)malloc(nsizeof(int)); for(intI=0; i<n;i++) {scanf ("%d",&A[i]); } intTime=gcd (m,n); inttemp,j; for(intI=0; i<time;i++) {Temp=A[i]; J=i; while(1) {A[j]=a[(j+n-m)%N]; J= (j+n-m)%N; if(j== (i+m)%N) {A[j]=temp; Break; }}} printf ("%d", a[0]); for(intI=1; i<n;i++) {printf ("%d", A[i]); }}
array element loop right shift problem (20)