【问题标题】:I get “Terminated due to timeout” in some test cases in hackerRank,how do I solve this?在hackerRank的一些测试用例中我得到“因超时而终止”,我该如何解决这个问题?
【发布时间】: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


【解决方案1】:

也许就地旋转数组而不是为每次旋转创建一个新数组?

static void rotation(int[] arr)
{
    int temp = arr[arr.length - 1];
    System.arraycopy(arr, 0, arr, 1, arr.length - 1);
    arr[0] = temp;
}

然后:

T = rotation(T);

变成:

rotation(T);

您还可以针对 k 小于 n 的情况进行优化,但如果您需要,我会将其作为练习留给您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2021-09-19
    • 2018-03-03
    • 2019-07-26
    • 1970-01-01
    相关资源
    最近更新 更多