【发布时间】:2016-07-28 19:07:13
【问题描述】:
我正在尝试在 HackerRank 中解决这个problem,但在某些测试用例中出现超时错误。有什么建议么? 以下是我的代码; 大多数测试用例都能正常工作,但其他测试用例会超时。
public class Solution
{
static int[] rotation(int[] arr)
{
int[] rot = new int[arr.length];
rot[0] = arr[arr.length - 1];
System.arraycopy(arr, 0, rot, 1, arr.length - 1);
return rot;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
int[] T = new int[n];
for (int i = 0; i < n; i++) {
T[i] = in.nextInt();
}
int[] indexes = new int[q];
for (int j = 0; j < q; j++) {
indexes[j] = in.nextInt();
}
in.close();
// Rotations
for (int ai = 0; ai < k; ai++) {
T = rotation(T);
}
// Queries
for (int qi = 0; qi < q; qi++) {
System.out.println(T[indexes[qi]]);
}
}
}
【问题讨论】:
-
我尝试使用 ArrayList 和 LinkedList 而不是数组。但结果相同。
-
我不明白你的评论,在输入格式部分它说我会在输入 n、k 和 q 的第一行,然后是表格项。接下来是 q 行,其中包含我将输出的 m 个索引。我就是这么做的。
标签: java performance for-loop