1008 數組元素循環右移問題 JAVA


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

一個數組A中存有N(>)個整數,在不允許使用另外數組的前提下,將每個整數循環向右移M(≥)個位置,即將A中的數據由(A0​​A1​​AN1​​)變換為(ANM​​AN1​​A0​​A1​​ANM1​​)(最后M個數循環移至最前面的M個位置)。如果需要考慮程序移動數據的次數盡量少,要如何設計移動的方法?

輸入格式:

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

輸出格式:

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

輸入樣例:

6 2
1 2 3 4 5 6

輸出樣例:

5 6 1 2 3 4

思路:
1. 將輸入的數組,按要求賦值給新的數組;
2. 打印新數組;
注意:需要考慮向右位移數字為0,或數字大於原始數組長度;(2個特殊情況)
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner in =new Scanner(System.in);
		int n =in.nextInt();
		int m =in.nextInt();
		int[]temp=new int[n];
		for(int i =0;i<n;i++)
		{
			temp[i]=in.nextInt();
		}
		temp=rightNum(temp, m);
		for(int i =0,count=0;i<n;i++,count++)
		{
			if(count==0)
			{
				System.out.print(temp[i]);
				count++;
			}
			else
			{
				System.out.print(" "+temp[i]);
			}
		}
		
	}
	public static int[] rightNum(int[]a,int b)
	{
		int[]result=new int[a.length];

		if(b>a.length)
		{
			b=b%a.length;
		}

		for(int i=0;i<a.length;i++)
		{
				if(i<b)
				{
					result[i]=a[a.length-b+i];
				}
				else if(b==0||b==a.length)
				{
					result=a;
				}
				else
				{
					
					result[i]=a[i-b];
				}
				
		}
		
		return result;
	}
	

}
 
           

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM