如何优化此代码(Counting Sort)

时间:2014-11-12 10:00:00

标签: java algorithm sorting

我试图解决经典计数排序问题。 我的o / p是对的,但超出了时间限制。如何优化以下代码。 我受到记忆限制。

时间限制:5秒 来源限制:50000字节

class TurboStart {
    static int integerArray[] = new int[1000001];

    public static void main(String[] args) throws NumberFormatException,
            IOException {
        int  i, j;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        j = Integer.parseInt(reader.readLine());

        while (j-- > 0) {
            integerArray[Integer.parseInt(reader.readLine())]++;
        }

        for (i = 0; i < 1000001; i++) {
            while (integerArray[i]-- > 0) {
                System.out.println(i);
            }

        }
    }
}

1 个答案:

答案 0 :(得分:1)

不要使用System.out.println,而是使用更聪明的方式编写输出(BufferedWriter?)。您的排序代码很好,因此瓶颈应该是I / O(这在编程竞赛中经常出现问题)。

相关问题