【发布时间】:2020-07-07 02:27:42
【问题描述】:
目标给定一个文件,第一行作为可用行数,求有多少对行是相互排列的。例如,AABA 是 BAAA 的排列。代码是用java编写的。这是我当前的代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
public class SpeedDemon {
public class Data{
byte[] dataValues;
byte duplicate=1;
int hashcode;
public Data(byte[] input) {
dataValues= new byte[128];
for (byte x : input) {
if (x==10){
break;
}
dataValues[x]++;
}
hashcode = Arrays.hashCode(dataValues);
}
public boolean equal(Data o){
return this.hashcode==o.hashcode&&Arrays.equals(o.dataValues, this.dataValues);
}
}
public int processData(String fileName){
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int size = Integer.parseInt(reader.readLine());
int arr_size = 2;
while (arr_size < size) {
arr_size *= 2;
}
Data[] map = new Data[arr_size];
int z = 0;
Data data;
int j;
for (int i = 0; i < size; i++) {
data = new Data(reader.readLine().getBytes());
j = data.hashcode;
j ^= (j >>> 16);
j &= (arr_size - 1);
while (true) {
if (map[j] == null) {
map[j] = data;
break;
} else {
if (map[j].equal(data)) {
z += map[j].duplicate++;
break;
} else {
j = j == arr_size - 1 ? 0 : j + 1;
}
}
}
}
return z;
}catch(Exception ex){ }
return 0;
}
public static void main(String[] args) {
System.out.println(new SpeedDemon().processData(args[0]));
}
}
我想知道有没有什么办法可以提高程序的时间效率?这是我课堂竞赛的一部分,有些人管理的运行时间快了 25% 左右。我尝试了不同的数组大小,这似乎效果最好。
【问题讨论】:
-
我只是好奇,你的输入文件有多大?您如何测试性能,之前和之后的常规时间戳或一些有效的基准?
-
我主要用这里的提交链接进行测试:speed-demon.herokuapp.com