一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A中的数据由(A0 A1……AN-1)变换为(AN-M …… AN-1 A0 A1……AN-M-1)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:每个输入包含一个测试用例,第1行输入N ( 1<=N<=100)、M(M>=0);第2行输入N个整数,之间用空格分隔。
输出格式:在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:6 2 1 2 3 4 5 6输出样例:
5 6 1 2 3 4
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 5 public class Main 6 { 7 static int N; 8 static int M; 9 static int[] A; 10 public static void main(String[] args) throws IOException 11 { 12 // System.out.println("..."); 13 BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); 14 String line=buf.readLine(); 15 String[] temp; 16 temp=line.split(" "); 17 N=Integer.parseInt(temp[0]); 18 M=Integer.parseInt(temp[1]); 19 M=M%N; 20 line=buf.readLine(); 21 temp=line.split(" "); 22 A=new int[temp.length]; 23 boolean[] a=new boolean[temp.length]; 24 for(int i=0;i<A.length;i++) 25 { 26 A[i]=Integer.parseInt(temp[i]); 27 a[i]=false; 28 } 29 30 // System.out.println("..."); 31 // System.out.println(A.length); 32 if(M==0) 33 ; 34 else 35 { 36 for(int i=0;i<M;i++) 37 { 38 int t1,t2; 39 t1=A[i]; 40 for(int j=i;a[(j+M)%a.length]==false;j+=M) 41 { 42 t2=A[(j+M)%A.length]; 43 A[(j+M)%A.length]=t1; 44 t1=t2; 45 a[(j+M)%a.length]=true; 46 } 47 } 48 } 49 for(int i=0;i<A.length-1;i++) 50 System.out.print(A[i]+" "); 51 System.out.println(A[A.length-1]); 52 53 54 } 55 }