PAT.B 1008 数组元素循环右移问题

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位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

6 2
1 2 3 4 5 6

输出样例:

5 6 1 2 3 4

要点记录:

注意交换方式,避免数字丢失。也可以不进行交换操作直接按交换后的顺序输出。

AC代码: 

1.不交换直接按结果顺序输出

#include <cstdio>

using namespace std;
int main(int argc, char const *argv[])
{
    int n,t;
    scanf("%d%d", &n , &t);
    int arr[n+1];
    for(int i = 1; i <= n; i++)
        scanf("%d", &arr[i]);
    
    t = t % n;//求模
    bool printed = false;//记录第一个是否被打印
    for(int i = n-t+1; i <= n; i++)
    {
        printf("%s%d", (i == n-t+1)?"":" ", arr[i]);
        printed = true;
    }
                                    //第一次打印后改变printed
    for(int i = 1; i < n-t+1; i++, printed = true)
        printf("%s%d", (printed == false)?"":" ", arr[i]);
    
    return 0;
}

2.交换后再输出 

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		sc.close();
		
		m = n -(m % n);
		int num = 0;
		for (int i = m; i < n; i++) {
			System.out.print(arr[i]);
			++num;
			if(num != n){
				System.out.print(" ");
			}
		}
		
		for (int i = 0; i < m; i++) {
			System.out.print(arr[i]);
			++num;
			if (num != n) {
				System.out.print(" ");
			}
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值