java - 如何优化此代码(计数排序)

标签 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);
            }

        }
    }
}

最佳答案

不要使用 System.out.println,而是使用一些更智能的方式来编写输出(BufferedWriter?)。您的排序代码很好,所以瓶颈应该是 I/O(这在编程竞赛中经常是 Java 的问题)。

关于java - 如何优化此代码(计数排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26884088/

相关文章:

java - 为什么 PriorityQueue.toString 返回错误的元素顺序?

python - 从标签和辨别值中学习阈值?

java - 在 fragment 之间传递蓝牙套接字

具有超过 4gb 元素的 Java 数组

java - 如何并行运行测试套件 XML 文件?

c# - 用二分查找查找数字——最大和最小操作数

algorithm - 洗牌数组的最佳算法

python - 对不一致数量的元素列表的最后一个元素进行排序

linux - 使用 Unix 排序对多个键进行排序——错误?

java - 使用 java 将 .txt 文件转换为 .csv 文件?