java - 加快全计数排序的方法

标签 java optimization string-concatenation counting-sort

我在 hackerrank 上遇到了一个问题。 https://www.hackerrank.com/challenges/countingsort4

由于超时,我的第一次尝试通过了除最后一个以外的所有测试用例。 在没有想出更有效的算法后,我通过使用 StringBuilder 而不是直接连接字符串来改进代码。这使运行时间从 5 多秒减少到 3.5 秒。

我的问题是有没有其他方法可以缩短运行时间? 谢谢。

以下是我的代码。

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int N = scanner.nextInt();
        scanner.nextLine();

        int[] oriNum = new int[N];        
        String[] oriStr = new String[N];
        int[] count = new int[100];
        int[] indices = new int[100];
        int[] output = new int[N];

        // save the originals and the count array
        for (int i = 0; i < N; i++) {
            oriNum[i] = scanner.nextInt();
            oriStr[i] = scanner.nextLine().trim();
            count[oriNum[i]]++;
        }

        // accumulate the count array
        indices[0] = 0;
        for (int i = 1; i < 100; i++) {
            indices[i] = indices[i-1] + count[i-1];
        }

        // output order
        for (int i = 0; i < N; i++) {
            int num = oriNum[i];
            output[indices[num]++] = i;
        }

        int bar = N/2;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < N; i++) {            
            int index = output[i];
            if (index < bar) 
                sb.append("- ");
            else 
                sb.append(oriStr[index]+ " ");
        }
        System.out.println(sb.toString());
    }
}

最佳答案

您应该尝试使用普通的缓冲读取器而不是扫描器。 Scanner 出奇地慢,我参加过一些编程比赛,其中 Scanner 是“超出时间限制”的唯一原因。

关于java - 加快全计数排序的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27288928/

相关文章:

java - preparedStatement.executeUpdate() 不插入值

java - 1 个 Activity 上的操作按钮?

python - 疯狂的字符串连接

javascript - 用于将字符填充到字符串末尾的jquery函数

java - 在 Java 中同时运行两个类

java - 我想检查 35 个文本字段中的任何一个是否有值,然后它的颜色会改变

c - 如何优化分配固定红利?

c# - 有什么优化此代码的建议吗?

Mysql按时间间隔分组优化

mysql - 响应为空时隐藏分隔符