PAT乙级——1008(数组操作,模拟)

版权声明:本文为博主原创文章,转载请注明原博客地址 https://blog.csdn.net/qunqunstyle99/article/details/82846088

题目: 数组元素循环右移问题 (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位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:
6 2
1 2 3 4 5 6

输出样例:
5 6 1 2 3 4

代码实现

//该代码尝试了很久都没有AC,得分14分,如后续改进,会继续更新的

import java.util.Scanner;
public class Main{
    public static void main(String []args){
        Scanner in = new Scanner(System.in);
        int num =in.nextInt();
        int move =in.nextInt();
        int num2 =2*num;
        int temp2;
        int temp[]=new int[num2];//建立两个长度的数组
        for(int i=0;i<num;i++)
            temp[i]=in.nextInt();
        temp2=num;
        for(int i=0;i<num;i++){//将全部后移move个数
            temp[temp2+move-1]=temp[temp2-1];
            temp2--;
        }
        temp2=move;
        for(int i=0;i<move;i++){//将数组最后面的数置于数组的开始
            temp[temp2-1]=temp[num+temp2-1];
            temp2--;
        }
        int count =0;
        for(int i=0;i<num;i++){
            if(count!=0)
                System.out.print(' ');
            System.out.print(temp[i]);
            count++;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qunqunstyle99/article/details/82846088