java - 代码厨师 : Time Limit Exceeded by the following java code

标签 java

这是问题的链接:- http://www.codechef.com/problems/INTEST/

以下是代码:-

import java.util.*;
import java.io.*;

class INTEST {
    public static void main(String...s) {
        String str = "";
        try {
            str = new BufferedReader(new InputStreamReader(System. in )).readLine();
        } catch (Exception e) {
            System.out.println(e);
        }
        String[] ar = str.split(" ");

        int n = Integer.parseInt(ar[0]);
        int k = Integer.parseInt(ar[1]);
        int count = 0;
        if (k <= 10000000) {
            int[] t = new int[n];

            for (int i = 0; i <= n - 1; i++) {
                try {
                    t[i] = Integer.parseInt(new BufferedReader(new InputStreamReader(System. in )).readLine());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (t[i] <= 1000000000) {
                    if (t[i] % k == 0) count++;

                } else break;
            }
        }
        System.out.println(count);

    }
}

我从 Scanner 改为 BufferedReader 来读取数据,但它无助于减少时间。

任何帮助我如何减少时间。谢谢。

问题:

此问题的目的是验证您用来读取输入数据的方法是否足够快,能够处理带有巨大输入/输出警告的问题。您预计在运行时每秒至少能够处理 2.5MB 的输入数据。

输入

输入以两个正整数 n k (n, k<=10^7) 开始。 接下来的 n 行输入包含一个正整数 ti,每行不大于 10^9。

输出

写入一个整数输出,表示有多少个整数 ti 可以被 k 整除。 示例

输入: 7 3

1

51

966369

7

9

999996

11

输出:

4

最佳答案

对象初始化的成本很高(即使用new)。你应该尽可能避免这种情况)。在这种情况下,您可以创建一个 Scanner 对象一次并重复使用它。

例如

class INTEST {
    public static void main(String...s) {
        String str = "";
         Scanner input=new Scanner(System.in);
        try {
            str = input.readLine();
        } catch (Exception e) {
            System.out.println(e);
        }
        String[] ar = str.split(" ");

        int n = Integer.parseInt(ar[0]);
        int k = Integer.parseInt(ar[1]);
        int count = 0;
        if (k <= 10000000) {
            int[] t = new int[n];

            for (int i = 0; i <= n - 1; i++) {
                try {
                    t[i] = Integer.parseInt(input.readLine());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (t[i] <= 1000000000) {
                    if (t[i] % k == 0) count++;

                } else break;
            }
        }
        System.out.println(count);

    }
}

注意: 代码还可以进行更多的优化。例如,使用 nextInt 而不是 nextLine,然后转换为 integer。此外,您始终可以假设输入,无需始终检查该值。

关于java - 代码厨师 : Time Limit Exceeded by the following java code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30844623/

相关文章:

java - 如何在java中编写简单的文本测试用例

java - 如何将规则存储在数据库中并在 java 文件中访问它们而不是在 Drools 中使用 .drl 文件?

java - JPA:如何仅覆盖@Embedded属性的列名

java - Android-利用Canvas优化画线

java - Spring boot中如何配置拦截器?

java - 默认构造函数,Java 与 C++

java - Swagger2 + Spring REST API 不工作

java - 如何最好地使用 Java 验证客户端与 elasticsearch 的连接?

java - 如何在 OpenGL 中移动相机

java - 部署 war 文件时设置 unix 权限的更好方法