加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 加速完整计数排序的方法

发布时间:2020-12-14 05:52:28 所属栏目:Java 来源:网络整理
导读:我在hackerrank遇到了一个问题. https://www.hackerrank.com/challenges/countingsort4 由于超时,我的第一次尝试通过了除最后一个之外的所有测试用例. 在未能提出更高效的算法之后,我通过使用StringBuilder而不是直接连接字符串来改进代码.这使得运行时间从5
我在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是“超出时间限制”的唯一原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读