我正在尝试解决人才伙伴的这个问题。 http://www.talentbuddy.co/challenge/52a9121cc8a6c2dc91481f8d5233cc274af0110af382f40f
我的代码编译并运行小输入,但对以下输入给出了错误的答案- http://tb-eval4.talentbuddy.co/5411559648d3e7eb5100024191810645628720530000.html
我的代码如下-
import java.util.*;
class MyClass {
public void tweets_per_second(Integer[] tps, Integer k) {
PriorityQueue<Integer> pq =new PriorityQueue<Integer>(k, new Comparator<Integer>(){
public int compare(Integer i1, Integer i2){
if (i1.intValue()< i2.intValue()){
return 1;
}
else if(i1.intValue() ==i2.intValue()){
return 0;
}
else {
return -1;
}
}
});
for(int i=0;i<tps.length;i++){
if (pq.size()<=k){
pq.add(tps[i]);
System.out.println(pq.peek());
}
else{
pq.remove(tps[i-k]);
pq.add(tps[i]);
System.out.println(pq.peek());
}
}
}
public static void main(String[] args) {
MyClass t = new MyClass();
Integer[] tps = {6,9,4,7,4,1};
t.tweets_per_second(tps, 3);
}
有人可以告诉我我做错了什么吗?任何帮助将不胜感激。谢谢。
最佳答案
代码完全正确。在页面末尾,您可以看到以下内容:
Error: your code didn't finish in less than 2 seconds.
它告诉你所有你需要知道的。
至于为什么你的代码很慢 - 虽然使用 PriorityQueue 或任何内置集合等总体上是个好主意,但在这种情况下却不是这样。我不想对它的实现方式做出有根据的猜测,但是 add、remove、peek
之一不是 O(1) 并且会占用您的时间。
关于java - Talent Buddy 推文每秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837732/