在解决在线法官的问题时,我尝试了这两种实现。
这两个实现做同样的事情。任务是报告给定数据集的重复条目。
实现 #1:将输入数据转换为字符串并添加到 HashSet。读取所有输入后,将显示相应的消息。
class Databse2 {
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());//number of test cases
int N=0,R=0,C=1;
while(t-->0){ //while there are more test cases
HashSet<String> set=new HashSet<String>();
StringTokenizer st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
N=Integer.parseInt(st.nextToken());
R=Integer.parseInt(st.nextToken());//Number of Rows of data
}
int ID=0,SC=0;boolean haha=true;
for(int i=0;i<R;i++){ //for number of rows read each record in the row
st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
ID=Integer.parseInt(st.nextToken());
SC=Integer.parseInt(st.nextToken());
}
String key=ID+""+SC;//convert to string,this combo is used to check for duplicates
haha=haha && set.add(key);
}
if(haha)
System.out.println("Scenario #"+C+": possible");
else System.out.println("Scenario #"+C+": impossible");
C++;
}
}
}
Running time #1 = 3.41 sec (for N number of test cases)
实施#2:与实施#1 中完成相同的任务,但以不同的方式完成。根据输入类型创建对象并添加到HashSet
.
class Database {
private int ID;
private int SC;
public Database(int ID,int SC) {
this.ID=ID;
this.SC=SC;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Database) ? ID==((Database)obj).ID:SC==((Database)obj).SC;
}
@Override
public int hashCode() {
return 31*(ID+SC);
}
public static void main(String[] args) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
int N=0,R=0,C=1;
while(t-->0) { //while there are more test cases
HashSet<Database> set=new HashSet<Database>();
StringTokenizer st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()) {
N=Integer.parseInt(st.nextToken());
R=Integer.parseInt(st.nextToken());//Number of rows of input
}
int ID=0,SC=0;
boolean haha=true;
for(int i=0;i<R;i++) { //Read data for each row from input set
st=new StringTokenizer(br.readLine());
while(st.hasMoreTokens()) {
ID=Integer.parseInt(st.nextToken());
SC=Integer.parseInt(st.nextToken());
}
haha=haha?set.add(new Database(ID, SC)):false;
}
String str=haha?"Scenario #"+C+": possible":"Scenario #"+C+": impossible";
System.out.println(str);
C++;
}
}
}
Running Time #2 = 2.74 sec (for N number of test cases)
是什么导致实施#2 更快?是 hashCode 方法吗?