Java 天才好友每秒推文数
我正试图从天才伙伴那里解决这个问题。 我的代码为小输入编译和运行,但为以下输入提供了错误的ans- 我的代码如下-Java 天才好友每秒推文数,java,algorithm,Java,Algorithm,我正试图从天才伙伴那里解决这个问题。 我的代码为小输入编译和运行,但为以下输入提供了错误的ans- 我的代码如下- import java.util.*; class MyClass { public void tweets_per_second(Integer[] tps, Integer k) { PriorityQueue<Integer> pq =new PriorityQueue<Integer>(k, new Comparator<Integer&
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);
}
import java.util.*;
类MyClass{
public void tweets_/秒(整数[]tps,整数k){
PriorityQueue pq=新的PriorityQueue(k,新的比较器(){
公共整数比较(整数i1、整数i2){
如果(i1.intValue() 对于(int i=0;i而言,代码完全正确。在页面末尾,您可以看到以下内容:
Error: your code didn't finish in less than 2 seconds.
这告诉你你需要知道的一切
至于为什么你的代码很慢——虽然使用PriorityQueue或任何内置集合等总体上是个好主意,但在这种情况下却不是这样。我不想对它是如何实现的进行有根据的猜测,但是添加、删除、查看中的一个不是O(1)并且会占用你的时间