【发布时间】:2021-09-23 04:40:07
【问题描述】:
我正在解决hacker-earth 上的一个问题,该问题是关于具有x 旋转步长的整数数组的右移。下面给出示例输入、输出:
输入:
测试用例 -- 1
[数组中的元素个数,旋转步数] -- 5 2
[数组元素] -- 1 2 3 4 5
输出:4 5 1 2 3
整个问题陈述可在互联网上找到,标题为 - Monk and Rotation
所以,我的代码在 5 个测试用例中运行良好,但在 1 个测试用例中因超过时间限制而失败。我尝试更改scanner 类并使用bufferedreader 和输入流阅读器来加快输入阅读速度,但仍然没有运气。下面是代码,请提出可以改进的地方。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.io.*;
class TestClass {
public static void main(String args[] ) throws Exception {
int noOfElements,stepsOfRotation;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(br.readLine());
while(testCases!=0)
{
String firstLine=br.readLine();
String[] parts=firstLine.split(" ");
noOfElements=Integer.parseInt(parts[0]);
stepsOfRotation=Integer.parseInt(parts[1]);
int[] arr=new int[noOfElements];
String secondLine=br.readLine();
String[] arrayElements=secondLine.split(" ");
for(int i=0;i<noOfElements;i++)
{
arr[i]=Integer.parseInt(arrayElements[i]);
}
stepsOfRotation %= noOfElements;
int result;
for(int i=0;i<noOfElements;i++)
{
result=arr[(i+(noOfElements-stepsOfRotation))%noOfElements];
System.out.print(result+" ");
}
System.out.println();
testCases--;
}
}
}
【问题讨论】:
标签: java arrays sorting java-8 bufferedreader