PAT-乙級-Java-1008
阿新 • • 發佈:2018-12-01
1008 陣列元素迴圈右移問題 (20 分)
一個數組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
Java程式碼實現:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); String s2 = sc.nextLine(); String[] split = s1.split(" "); int num = Integer.parseInt(split[0]);//輸入的整數個數 int move = Integer.parseInt(split[1]);//迴圈右移位數 int [] arr = new int [move+num]; String [] split1 = s2.split(" "); for(int i = 0;i<num;i++) { arr[i] = Integer.parseInt(split1[i]); } if(num>move) { move(move,num,arr); }else {//移動的幅度大於資料長度 move(move-num,num,arr); } } public static void move(int move,int num,int [] arr) { //後移 for(int i = num-1;i>=0;i--) { arr[i+move] = arr[i]; } //後邊調頭 for(int i = 0;i<move;i++) { arr[i] = arr[num+i]; } for(int i = 0;i<num;i++) { if(i != num-1) { System.out.print(arr[i]+" "); }else { System.out.println(arr[i]); } } } }