两个测试点超时,为什么窝的代码这么容易超时啊,难受,判断素数和输入嵌套,真的不知道怎么才能不超时,有木有好心人评论区给点建议QAQ
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.HashMap;
public class p1059 {
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int num=Integer.parseInt(br.readLine());
HashMap<Integer, String> hashMap = new HashMap<>();
//得到初始化的结果集
for (int i = 0; i < num; i++) {
int id=Integer.parseInt(br.readLine());
if(i!=0){
if(isPrime(i+1)){//判断排名是否为素数
hashMap.put(id, "Minion");
}else{
hashMap.put(id,"Chocolate" );
}
}else{
hashMap.put(id,"Mystery Award" );
}
}
//输入要查找的ID内容
int searchCount=Integer.parseInt(br.readLine());
String[] result=new String[searchCount];
for (int i = 0; i < searchCount; i++) {
int id=Integer.parseInt(br.readLine());
DecimalFormat df=new DecimalFormat("0000");
String idStr=df.format(id);
if(hashMap.containsKey(id)){
//格式化ID
if(hashMap.get(id)!="hasGotten") {
result[i] = idStr + ": " + hashMap.get(id);
hashMap.put(id,"hasGotten" );
}else{
result[i] = idStr +": Checked";
}
}else{
//格式化ID
result[i]=idStr+": Are you kidding?";
}
}
for (String s : result) {
System.out.println(s);
}
}
public static boolean isPrime(int num){
if(num==2){
return true;
}
int i=1;
int count=0;
while(i<=Math.ceil(Math.sqrt(num))){
if(num%i==0){
count++;
}
i++;
}
if(count>1){
return false;
}else{
return true;
}
}
}