java - Talent Buddy 推文每秒

标签 java algorithm

我正在尝试解决人才伙伴的这个问题。 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/

相关文章:

java - 绑定(bind)项目内部类的可访问性不一致,但无法获得正确的转换语法

C - 循环次数减少的冒泡排序

JAVA 8 在启动时崩溃并出现 fatal error 日志 - Solaris 10 (sparc)

java - junit日志杂乱,为什么会重复语句?

python - 查找一组间隔中的重叠间隔

excel - 如何为我的数据集确定最佳数据结构/实现?

arrays - O(1) 空间和 O(n) 时间的循环置换

c++ - 在 C++ 中用字符串中更多的字符替换一个字符,而不删除其他字母

java - JFrame 实例无法可视化添加的组件

java - 将 json 格式的参数数组传递给 SOAP Web 服务?