本題要求實現一個對數組進行循環左移的簡單函數:一個數組a中存有n(>0)個整數,在不允許使用另外數組的前提下,將每個整數循環向左移m(≥0)個位置,即將a中的數據由(a0a1⋯an−1)變換為(am⋯an−1a0a1⋯am−1)(最前面的m個數循環移至最后面的m個位置)。如果還需要考慮程序移動數據的次數盡量少,要如何設計移動的方法?
輸入格式:
輸入第1行給出正整數n(≤100)和整數m(≥0);第2行給出n個整數,其間以空格分隔。
輸出格式:
在一行中輸出循環左移m位以后的整數序列,之間用空格分隔,序列結尾不能有多余空格。
輸入樣例:
8 3
1 2 3 4 5 6 7 8
輸出樣例:
4 5 6 7 8 1 2 3
代碼:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n,m,t; int a[] = new int[100]; n = sc.nextInt(); m = sc.nextInt(); for(int i=0;i<n;i++) a[i]= sc.nextInt(); for(int i=1;i<=m;i++) { t=a[0]; for(int j=0;j<n-1;j++) a[j]=a[j+1]; a[n-1]=t; } System.out.print(a[0]); for(int i=1;i<n;i++) System.out.printf(" %d",a[i]); } }