因此,我尝试在Java中搜索数组列表,并创建一个直方图,该直方图由字符串的长度与长度在大型文本文件中出现的频率组成。我已经想出了一个强力算法,但它太慢了,不能用于大型数据文件。有没有更有效的方法来处理数组列表?我已经包含了我想出的暴力方法。
for (int i = 0; i < (maxLen + 1); i++)
{
int hit = 0;
for (int j = 0; j < list.size(); j++)
{
if (i == list.get(j).length())
++hit;
histogram[i] = hit;
}
}发布于 2012-10-24 01:28:32
这是非常低效的。
不是遍历每个可能的长度值,然后遍历每个可用单词,而是简单地遍历文档中的可用单词并计算它们的长度,怎么样?
例如:
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(int i=0; i<list.size(); i++) {
String thisWord = list.get(i);
Integer theLength = (Integer)(thisWord.length());
if(frequencies.containsKey(theLength) {
frequencies.put(theLength, new Integer(frequencies.get(theLength).intValue()+1));
}
else {
frequencies.put(theLength, new Integer(1));
}
}然后,如果键不存在于HashMap中,您就知道文档中不存在该长度的单词。如果该键确实存在,则可以准确地查找发生了多少次。
注意:此代码示例的某些方面是为了防止有关装箱和取消装箱的任何其他混淆。可以写得稍微干净一点,我肯定会在生产环境中这样做。此外,它还假设您不了解任何最小或最大长度的单词(因此更加灵活、可伸缩性和通用性更强)。否则,简单地声明原始数组的其他技术将同样有效(参见Jon Skeet的答案)。
对于利用自动装箱的更干净的版本:
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(int i=0; i<list.size(); i++) {
String thisWord = list.get(i);
if(frequencies.containsKey(thisWord.length()) {
frequencies.put(thisWord.length(), frequencies.get(thisWord.length())+1);
}
else {
frequencies.put(thisWord.length(), 1);
}
}发布于 2012-10-24 01:29:19
为什么不在列表中循环一次呢
int[] histogram = new int[maxLen + 1]; // All entries will be 0 to start with
for (String text : list) {
if (text.length() <= maxLen) {
histogram[text.length()]++;
}
}这现在只是O(N)。
https://stackoverflow.com/questions/13035989
复制相似问题