我现在正在解决Hackerrank上的一个问题,并且我相信我的逻辑或多或少是正确的,但是较大的数据集会降低性能,从而给我一个“错误”的答案。这是问题的链接,因此您可以检查出该问题:

https://www.hackerrank.com/challenges/qheap1

我想知道如何提高此脚本的性能,以允许使用更大的数据集。我有一个与扫描仪有关的预感,但我不知道为什么。

public class Solution {
    private static final int ADD = 1;
    private static final int DELETE = 2;
    private static final int GET = 3;
    private static final int TICK = 1;
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        PrintStream out = System.out;
        int n = in.nextInt();
        int[] heap = new int[n];

        int a = 0;
        while (a < n) {
            a = 0;
            int q = in.nextInt();

            switch(q) {
                case(ADD):
                    int nextAdd = in.nextInt();
                    /*out.println("ADD " + next);*/
                    int b = 0;
                    while (b < n) {
                        /*out.println(heap[b]);*/
                        if (heap[b] == 0) {
                            heap[b] = nextAdd+TICK;
                            /*printArray(heap);*/
                            b = n-1;
                        }
                        b++;
                    }
                    /*printArray(heap);*/
                    break;
                case(DELETE):
                    int c = 0;
                    int nextDelete = in.nextInt();
                    while (c < n) {
                        if (heap[c]-TICK == nextDelete) {
                            heap[c] = 0;
                            c = n-1;
                        }
                        c++;
                    }
                    /*printArray(heap);*/
                    break;
                case(GET):
                    Arrays.sort(heap);
                    int d = 0;
                    while (d < n) {
                        if (heap[d] != 0) {
                            out.println(heap[d]-TICK);
                            d = n-1;
                        }
                        d++;
                    }
                    /*printArray(heap);*/
                    break;
            }
            a++;
            /*printArray(heap);*/
        }
    }

    public static void printArray(int[] ar) {
        String str = "";
        for (int i : ar) {
            str += i + " ";
        }
        System.out.println(str);
    }
}

最佳答案

查看您的代码,我能发现的唯一直接问题是该行

out.println(heap[d]-TICK);


没有被注释掉。这可能意味着您的Java程序(不,不是脚本,请注意!)正在执行许多IO操作。与程序中进行的其他操作相比,这些操作非常昂贵。

因此,将其注释掉,然后看看会发生什么。

10-05 20:29
查看更多