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

一個數組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個位置)。如果需要考慮程序移動數據的次數儘量少,要如何設計移動的方法?

輸入格式:

每個輸入包含一個測試用例,第1行輸入N(1≤N≤100)和M(≥0);第2行輸入N個整數,之間用空格分隔。

輸出格式:

在一行中輸出循環右移M位以後的整數序列,之間用空格分隔,序列結尾不能有多餘空格。

輸入樣例:


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Scanner;


public class Main{
	public static void revise(int []ans,int begin,int end) {
		for(int i=begin, j = end;i<j;i++,j--) {
			int temp = ans[i];
			ans[i] = ans[j];
			ans[j] = temp;
		}
	}
	public static void main(String[] args) {
		Scanner sc= new Scanner(System.in);
		int total = sc.nextInt();
		int move = sc.nextInt();
		move = move%total;
		int[] ans = new int [total+1];
		for(int i = 1;i<=total;i++) {
			ans[i]=sc.nextInt();
		}
		revise(ans,1,total-move);
		revise(ans,total-move+1,total);
		revise(ans,1,total);
		for(int i =1;i<=total;i++) {
			if(i==1) {
				System.out.print(ans[i]);
			}
			else
			System.out.print(" "+ans[i]);
		}
		
	}
}


 

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