【发布时间】:2022-02-04 12:50:49
【问题描述】:
我正在解决这个问题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
他们说:
您应该能够处理 每个至少 2.5MB 的输入数据 运行时第二个。
修改后的代码
谢谢大家...我修改了我的代码并且它工作了...在这里...
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);
}
问候
沙恨沙
【问题讨论】:
-
如果您没有将这个数组用于任何有用的事情,为什么还要使用
int[] t?你可以改用int t。 -
这看起来像是 ACM-ICPC 问题的输入代码,这是整个“程序”吗?从哪里超时?在线法官?您能给我们一些示例输入吗?
-
是的,这就是整个程序......他们在他们的服务器上运行代码......他们给了我们 8 秒的时间来完成这个特定的程序......他们说“你应该是能够在运行时每秒处理至少 2.5MB 的输入数据。”
-
输入格式是这样的吗?或者您在每个 int 之间是否有未知数量的空白?还是每个数字都在不同的行?
-
第一行 n 和 k 之间有一个空格……之后,每个数字都换行……
标签: java optimization io user-input inputstream