一 个 数 组 A 中 存 有 N ( > 0 ) 个 整 数 , 在 不 允 许 使 用 另 外 数 组 的 前 提 下 , 将 每 个 整 数 循 环 向 右 移 M ( ≥ 0 ) 个 位 置 , 即 将 A 中 的 数 据 由 ( A 0 A 1 ⋯ A N − 1 ) 变 换 为 ( A N − M ⋯ A N − 1 A 0 A 1 ⋯ A N − M − 1 ) ( 最 后 M 个 数 循 环 移 至 最 前 面 的 M 个 位 置 ) 。 如 果 需 要 考 虑 程 序 移 动 数 据 的 次 数 尽 量 少 , 要 如 何 设 计 移 动 的 方 法 ? 一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数据由(A 0 A 1 ⋯A N−1 )变换为(A N−M ⋯A N−1 A 0 A 1 ⋯A N−M−1 )(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法? 一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数据由(A0A1⋯AN−1)变换为(AN−M⋯AN−1A0A1⋯AN−M−1)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:
每个输入包含一个测试用例,第1行输入N(1≤N≤100)和M(≥0);第2行输入N个整数,之间用空格分隔。
输出格式:
在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:
6 2
1 2 3 4 5 6
输出样例:
5 6 1 2 3 4
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N,M;
N = scanner.nextInt();
M = scanner.nextInt();
int temp[] = new int[N];
for(int i=0;i<N;i++){
temp[i] = scanner.nextInt();
}
for(int i=0;i<M;i++){
int t = temp[N-1];
for(int j=N-1;j > 0;j--){
temp[j] = temp[j-1];
}
temp[0] = t;
}
for(int i=0;i<N-1;i++){
System.out.print(temp[i] + " ");
}
System.out.print(temp[N-1]);
}
}
题解二:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(),m = scanner.nextInt();
m = m % n;
int t = n - m,temp;
int[] num = new int[n];
for(int i=0;i<n;i++){
num[i] = scanner.nextInt();
}
for(int i=0;i<m;i++){
temp = num[t+i];
for(int j=t+i;j>i;j--){
num[j] = num[j-1];
}
num[i] = temp;
}
for(int i=0;i<n-1;i++){
System.out.print(num[i]+" ");
}
System.out.print(num[n-1]);
}
}
第二种方法效率高,但是要注意m可能大于n。