The main reasons are
Scanner
is pretty slow
System.in
is unbuffered
By using a BufferedReader
instead of the Scanner
you get it to barely acceptable levels. The following approach runs in roughly 8.2 seconds and get's accepted.
public class Main {
public static void main(String args[]) throws java.io.IOException {
java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in);
java.io.BufferedReader br = new java.io.BufferedReader(isr, 16 * 1024);
String[] line0 = br.readLine().split(" ");
int n, k, m = 0;
n = Integer.parseInt(line0[0]);
k = Integer.parseInt(line0[1]);
for (int c = 0; c < n; c++) {
if (Integer.parseInt(br.readLine()) % k == 0)
m++;
}
System.out.println(m);
}
}
But it's still really slow compared to the top scoring solutions that run in under 2 seconds.
I've got it down to a bit over 2 seconds by reading into a byte[]
buffer and doing custom number parsing based on that buffer roughly like the following incomplete piece (which just prints the parsed numbers)
public class Main {
public static void main(String args[]) throws java.io.IOException {
byte[] buffer = new byte[16 * 1024];
int currentNumber = 0;
boolean inNumber = false;
int read;
while((read = System.in.read(buffer)) >= 0) {
for (int i = 0; i < read; i++) {
char c = (char) buffer[i];
if (c >= '0' && c <= '9') {
inNumber = true;
currentNumber = currentNumber * 10 + (c - '0');
} else if (inNumber) {
inNumber = false;
System.out.println("I've read number: " + currentNumber);
currentNumber = 0;
}
}
}
}
}
See http://ideone.com/lQ4ImB for above code with input
The reason why this is so much faster is basically that there is almost 0 overhead in reading & parsing the input into numbers. BufferedReader
in comparison is transforming each line into a String
(thus creating a new Object), then parses that String. Above approach allocates no new Objects besides the single byte[]
buffer.
You are expected to be able to process at least 2.5MB of input data per second at runtime.
Are you expecting your user to be able to type that much data that fast into the console? Because that sounds impossible to me. – MrLore Jan 7 at 12:26Time Limit Exceed Error
– Rhs Jan 7 at 17:10