I have solved hackerrank Java Map Problem but I had timeout result for 2 cases. When I changed just the printf line problem solved. However I could not understand why it is ? Here my code:
import java.util.*;
import java.io.*;
class Solution{
private static HashMap<String, Integer> phoneBook = new HashMap<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String search = "";
int n=in.nextInt();
in.nextLine();
for(int i=0; i<n; i++) {
String name=in.nextLine();
int phone=in.nextInt();
phoneBook.put(name, phone);
in.nextLine();
}
while(in.hasNext()) {
search = in.nextLine();
if (phoneBook.get(search) != null)
System.out.printf(search + "=" + phoneBook.get(search) + "\n"); // this works
// System.out.printf("%s=%d\n", search, phoneBook.get(search)); // this does not work why ?
else
System.out.println("Not found");
}
}
Formatter.format() takes timeFormatter.format() (and its shortcut System.out.printf()) requires parsing, validating and formatting. All that takes a huge amount of time.
So just dump the data as quick as possible. Hackerrank requires you to make fast programs, so just do that: a fast program. Concatenate your items instead of formatting them. Also, if you have no parameter, just use System.out.println() instead of System.out.printf.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With