【发布时间】:2021-11-28 22:26:54
【问题描述】:
我被要求制作这个程序。下面是示例程序流程。
// first input: how many data you want to input. Data is consisted of name and phone number. Both are string.
3
// here is the data-entry procedure. I use HashMap. 3 iteration to input the names and phone numbers
hans
12345678
dion
123456789
harry
12345671
// after the data is entered, I entered (also 3, taken from the entry at first input) 3 names to be searched within the HashMap. This can be any name that you can think of. As long as the name are in the HashMap, the program will display the person's name and his/her phone num.
herry
hans
harry
//result will be written as 'not found' if the key (name) is not present in HashMap. This is the sample output
not found
hans=12345679
harry=12345671
其实我的程序已经运行成功了。这是我正在使用的代码,输出的屏幕截图附在下面。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class HM2a {
static List<String> listQuery = new ArrayList<String>();
public static void loop(String name, HashMap<String, String> phonebook) {
String key, value;
String result = "";
for (Map.Entry<String, String> entry : phonebook.entrySet()) {
key = entry.getKey();
value = entry.getValue();
if (name.equals(key)) {
result = key + "=" + value;
listQuery.add(result);
return;
}
}
result = "Not found";
listQuery.add(result);
}
public static void main(String[] args) throws IOException {
HashMap<String, String> phonebook = new HashMap<String, String>();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
int entries = Integer.parseInt(bufferedReader.readLine());
String query = "";
String list = "";
for (int i = 0; i < entries; i++) {
String name = bufferedReader.readLine();
String phonenum = bufferedReader.readLine();
name = name.toLowerCase();
phonebook.put(name, phonenum);
}
for (int i = 0; i < entries; i++) {
query = bufferedReader.readLine();
query = query.toLowerCase();
loop(query, phonebook);
}
for (int i = 0; i < listQuery.size(); i++) {
System.out.println(listQuery.get(i));
}
} catch (Exception e) {
System.out.println(e);
}
}
}
问题是,我的代码是由我的校园使用的本地自动评分器(类似于 HackerRank 的)评分的,它一直说(来自测试用例)我的运行时间总是超过 5 秒,有 3 个用例。不幸的是,我不能问测试用例是什么。
有什么方法可以让我的代码更高效,尤其是搜索算法,以减少运行时间?老实说,我已经没有想法了。一开始我使用scanner,但后来发现scanner占用大量内存,我将其改为BufferedReader。它很麻烦,但现在我面临运行时问题。
【问题讨论】:
-
为什么要遍历 hashmap 条目集并将每个条目的键与
name进行比较,而不是使用Map.get(name)?
标签: java search arraylist hashmap bufferedreader