天天看點

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

1008 數組元素循環右移問題 (20 分)

一個數組A中存有N(>0)個整數,在不允許使用另外數組的前提下,将每個整數循環向右移M(≥0)個位置,即将A中的資料由(A​0A1⋯A​N−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 sc = new Scanner(System.in);
		int N = sc.nextInt();
		int Z = sc.nextInt();
		int M = Z%N;
		int [] A = new int [N];
		int count = 0;
		for (int i = 0; i < N; i++) {
			int num = sc.nextInt();
			if(i+M<N){
				A[i+M] = num;
			}else{
				A[count] = num;
				count++;
			}
		}
		for (int i = 0; i < N; i++) {
			if(i != N-1){
				System.out.print(A[i]+" ");
			}else{
				System.out.print(A[i]);
			}

		}
	}
}