本文介绍了哪种是在Java中获取输入的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决此。

这是我的代码:

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);

    }
}

但是当我提交它时,它得到了时间。请尽可能帮我优化。

But when I submit it, it get's timed out. Please help me optimize this to as much as is possible.

示例

输入:

7 3
1
51
966369
7
9
999996
11

输出:

4

他们说:

修改后的代码

谢谢大家...我修改了我的代码并且有效...这是... ....

Thank you all...I modified my code and it worked...here it is....

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

问候

shansha

推荐答案

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

This could be slightly faster, based on limc's solution, BufferedReader should be faster still though.

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);

    }
}

这篇关于哪种是在Java中获取输入的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:53