PAT 乙級1008. 數組元素循環右移問題 (JAVA版)

一個數組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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] line1 = sc.nextLine().split(" ");
        String[] line2 = sc.nextLine().split(" ");

        int n = Integer.parseInt(line1[0]);
        int t = Integer.parseInt(line1[1]);
        int[] a = new int[n];
        for (int i = 0; i < a.length; i++) {
            a[i] = Integer.parseInt(line2[i]);
        }
        for (int i = 0; i < t; i++) {
            move(a);
        }
        print(a);

    }

    private static void move(int[] arr) {
        int t = arr[0];
        arr[0] = arr[arr.length-1];
        for (int i = arr.length -1; i > 1; i--) {
            arr[i] = arr[i-1]; 
        }
        arr[1] = t;

    }
    private static void print(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length -1) {
                System.out.print(arr[i]);
            }else{
                System.out.print(arr[i] + " ");

            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章