尝试在Lintcode上解决549. Top K Frequent Words (Map Reduce)时遇到问题。我尽力进行调试,但是仍然不明白为什么我的代码不能100%被接受。
class Node{
String key;
Integer count;
Node(String k, Integer c){
key = k; count = c;
}
}
public class TopKFrequentWords {
public static class Map {
public void map(String tmp_, Document value,
OutputCollector<String, Integer> output) {
String [] words = value.content.split(" ");
for(String word: words){
if(word.length() > 0) output.collect(word, 1);
}
}
}
public static class Reduce {
private Queue<Node> min_heap;
private int K;
private Comparator<Node> nodeComparator = new Comparator<Node>(){
public int compare(Node a, Node b){
return (a.count != b.count) ? a.count - b.count : b.key.compareTo(a.key);
}
};
public void setup(int k) {
min_heap = new PriorityQueue<Node>(k, nodeComparator);
K = k;
}
public void reduce(String key, Iterator<Integer> values) {
Integer sum = 0;
while(values.hasNext()) sum += values.next();
Node res = new Node(key, sum);
if(min_heap.size() < K) min_heap.offer(res);
else{
if(nodeComparator.compare(res, min_heap.peek()) > 0){
min_heap.poll();
min_heap.offer(res);
}
}
}
public void cleanup(OutputCollector<String, Integer> output) {
Stack<Node> stack = new Stack<>();
while(!min_heap.isEmpty()) stack.push(min_heap.poll());
while(!stack.isEmpty()){
Node cur = stack.pop();
output.collect(cur.key, cur.count);
}
}
}
}
这是我第一次发布问题。谁能帮我?谢谢! 在一个测试案例中,我的输出是:
"e", 984
"g", 972
"d", 953
"h", 952
"a", 933
"f", 928
"b", 925
"c", 873
"fg", 168
"hf", 164
"ha", 159
"ec", 152
"fa", 151
"da", 151
"gf", 150
"bd", 149
"ah", 146
"eh", 146
"bc", 145
"hc", 143
但答案是:
"e", 984
"g", 972
"d", 953
"h", 952
"a", 933
"f", 928
"b", 925
"c", 873
"fg", 168
"hf", 164
"ha", 159
"ec", 152
"da", 151
"fa", 151
"gf", 150
"bd", 149
"ah", 146
"eh", 146
"bc", 145
"ba", 143
当具有相同的计数并按字母顺序排序时,似乎在“ fa”,“ da”和最后一行中出现了问题。但是如何修改比较器代码?