简体   繁体   中英

Talent Buddy Tweets per second

I am trying to solve this question from talent buddy. http://www.talentbuddy.co/challenge/52a9121cc8a6c2dc91481f8d5233cc274af0110af382f40f

My code compiles and runs for small input, but is giving wrong ans for the following input- http://tb-eval4.talentbuddy.co/5411559648d3e7eb5100024191810645628720530000.html

My Code is as follows -

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);
}

}

Can someone please let me know what am I doing wrong? Any help will be appreciated. Thanks.

The code is entirely correct. At the end of the page you can see the following:

Error: your code didn't finish in less than 2 seconds.

Which tells you all you need to know.

As to why your code is slow - while using PriorityQueue or any built in collections etc is overall a good idea, it is very much not so in this case. I don't want to make educated guesses about how it's implemented, but one of add, remove, peek is not O(1) and eats up your time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM