1008. 数组元素循环右移问题 (20)

来源:互联网 发布:ubuntu 火狐浏览器 编辑:程序博客网 时间:2024/06/08 10:26


1008. 数组元素循环右移问题 (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard

一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A中的数据由(A0A1……AN-1)变换为(AN-M …… AN-1 A0 A1……AN-M-1)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?

输入格式:每个输入包含一个测试用例,第1行输入N ( 1<=N<=100)、M(M>=0);第2行输入N个整数,之间用空格分隔。

输出格式:在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:
6 21 2 3 4 5 6
输出样例:

5 6 1 2 3 4

我看了一下其他人的解答,觉得他们做的没有按照题目的要求,题目明确说了不许使用额外的数组辅助。我就只用了一个变量解决了,下面我的答案希望你们能有所收获:

package mypackage;

import java.util.Scanner;

public class ReverseData { public static void main(String[] args) {  new ReverseData().reverse(); }

 private void reverse() {  @SuppressWarnings("resource")  Scanner cin = new Scanner(System.in);  String str_times = cin.nextLine();  String data = cin.nextLine();  System.out.println("str_times:" + str_times + ";data:" + data);  // 将字符转为整型  String[] times = str_times.split(" ");  int lengh = Integer.parseInt(times[0]);// 数组长度  int m = Integer.parseInt(times[1]);// 数组右移的位数  String[] str_datas = data.split(" ");// 数组的值  int[] values = new int[lengh];  for (int i = 0; i < values.length; i++) {   values[i] = Integer.parseInt(str_datas[i]);  }  // 数组右移处理  int[] goright = null;  for (int i = 0; i < m; i++) {   goright = goright(values);  }  for (int i = 0; i < goright.length - 1; i++) {   System.out.print(goright[i] + " ");  }  System.out.print(goright[goright.length - 1]); }

 public int[] goright(int[] values) {  int a = values[values.length - 1];// 保存数组最右边的数值  for (int i = values.length - 2; i > -1; i--) {// 从倒数第二位开始赋值   values[i + 1] = values[i];  }  // 处理第一位  values[0] = a;  return values; }}

0 0
原创粉丝点击