其他分享
首页 > 其他分享> > 哪种方法最有效?

哪种方法最有效?

作者:互联网

我正在解决这个question.

这是我的代码:

import java.io.IOException;
import java.util.Scanner;


public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] t = new int[n];
        int count = 0;
        for (int i = 0; i < n; i++) {
            t[i] = sc.nextInt();
            if (t[i] % k == 0) {
                count++;
            }
        }
        System.out.println(count);

    }
}

但是当我提交它时,它就超时了.请帮助我尽可能优化这一点.

输入:

7 3
1
51
966369
7
9
999996
11

输出:

4

他们说 :

You are expected to be able to process
at least 2.5MB of input data per
second at runtime.

修改后的CODE

谢谢大家…我修改了我的代码,它起作用了…在这里…

 public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] input = br.readLine().split(" ");
        int n = Integer.parseInt(input[0]);
        int k = Integer.parseInt(input[1]);
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (Integer.parseInt(br.readLine()) % k == 0) {
                count++;
            }
        }
        System.out.println(count);
    }

问候

Shahensha

解决方法:

根据limc的解决方案,这可能会更快一些,但是BufferedReader应该还是更快.

import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int count = 0;
        while (true) {
            try {
                if (sc.nextInt() % k == 0) {
                    count++;
                }
            } catch (NoSuchElementException e) {
                break;
            }
        }
        System.out.println(count);

    }
}

标签:optimization,io,user-input,java,inputstream
来源: https://codeday.me/bug/20191208/2093638.html