【发布时间】:2013-06-17 03:52:05
【问题描述】:
我尝试了两种方法。
-
使用 HashMap 计算每个项目的计数,然后导航地图
HashMap<Integer, Integer> doc_counts = new HashMap<Integer, Integer>(); for (int i = 0; i < p; ++i) { int doc = alld[i]; Integer count = doc_counts.get(doc); if (null == count) count = 0; doc_counts.put(doc, count + 1); } // to now it cost 200ms already for (Entry<Integer, Integer> item : doc_counts.entrySet()) { heapCheck(h, hsize, item.getKey(), item.getValue()); // heap sort top hsize items } -
先对数组进行排序,然后使用堆排序得到前N个。
Arrays.sort(alld, 0, p); // the sort costs about 160ms int curr = alld[0]; int count = 0; for(int i = 0; i < p; i++) { int doc = alld[i]; if(doc == curr) { ++count; } else { ++nHits; //curr += base; heapCheck(h, hsize, curr, count); curr = doc; count = 1; } } // // Handle the last document that was collected. heapCheck(h, hsize, curr, count);
对一个包含 1,600,000 个元素的数组进行测试表明,第二种方法花费了大约 170 毫秒,并且大部分时间都花在了排序上(大约 160 毫秒),而第一种方法花费了 200 毫秒,即使只是将所有元素添加到 HashMap 中。如何提高性能、找到更快的映射或排序函数或将其更改为并行函数以使用多线程?
【问题讨论】:
-
@assylias 您提到的 3 个链接是关于另一个问题“前 N 个”,但不是“前 N 个出现”。事实上,heapCheck 是“top N”问题的最佳解决方案,但它只是整个问题的一部分。
-
抱歉,我看错了你的问题。
-
你试过第一个
HashMap<Integer, Integer> doc_counts = new HashMap<Integer, Integer>(alld.length, 1.0f);吗? -
@assylias 这个我试过了,性能提升不大,还是170ms左右
-
您是否尝试过使用 IntMap
或 multisets ?它们不在 Java 公共库中,但可能真的更快。
标签: java algorithm performance sorting collections