1008 数组元素循环右移问题 (20 分)
一个数组A中存有N(>)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥)个位置,即将A中的数据由(A0A1⋯AN−1)变换为(AN−M⋯AN−1A0A1⋯AN−M−1)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:
每个输入包含一个测试用例,第1行输入N(1)和M(≥);第2行输入N个整数,之间用空格分隔。
输出格式:
在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:
6 2
1 2 3 4 5 6
输出样例:
5 6 1 2 3 4
思路:
1. 将输入的数组,按要求赋值给新的数组;
2. 打印新数组;
注意:需要考虑向右位移数字为0,或数字大于原始数组长度;(2个特殊情况)
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in =new Scanner(System.in); int n =in.nextInt(); int m =in.nextInt(); int[]temp=new int[n]; for(int i =0;i<n;i++) { temp[i]=in.nextInt(); } temp=rightNum(temp, m); for(int i =0,count=0;i<n;i++,count++) { if(count==0) { System.out.print(temp[i]); count++; } else { System.out.print(" "+temp[i]); } } } public static int[] rightNum(int[]a,int b) { int[]result=new int[a.length]; if(b>a.length) { b=b%a.length; } for(int i=0;i<a.length;i++) { if(i<b) { result[i]=a[a.length-b+i]; } else if(b==0||b==a.length) { result=a; } else { result[i]=a[i-b]; } } return result; } }