码迷,mamicode.com
首页 > 编程语言 > 详细

PTA 7-1 数组元素循环右移问题 (20分)

时间:2020-02-01 21:35:42      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:col   bsp   next   str   nbsp   inf   public   数组   scanner   

技术图片

输入样例:

6 2
1 2 3 4 5 6

输出样例:

5 6 1 2 3 4

 1 import java.util.Scanner;
 2 public class Main {
 3     public static void main(String[] args) {
 4         Scanner sc=new Scanner(System.in);
 5         int n=sc.nextInt();
 6         int m=sc.nextInt();
 7         int a[]=new int[n];
 8         for(int i=0;i<n;i++){
 9             a[(i+m)%n]=sc.nextInt();//数组位置的逻辑需要清楚
10         }
11         System.out.print(a[0]);
12         for(int i=1;i<n;i++){
13             System.out.print(" "+a[i]);
14         }
15     }
16 }

 有参考网上的各种答案,但是看别人的代码实在是太长了 看不下去(看不懂)就开始研究自己写 可能和别人方法都是一样的。

一开始的做法是三个for循环 第一个用来赋值 第二个移动 第三个输出 当时就觉得有点繁琐,想着一会再简化一下,结果算数组位置的时候就算错了 【(i+m)%n】 就干脆全删掉,直接写自己想的简化的代码,然后碰巧答案正确。

第九行代码a[(i+m)%n]是最重要的。



PTA 7-1 数组元素循环右移问题 (20分)

标签:col   bsp   next   str   nbsp   inf   public   数组   scanner   

原文地址:https://www.cnblogs.com/Flyfishy/p/12249871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!