Top K Vote

题目:
输入votes(candidateId, timeStamp)和截止时间T,问得票数前K个人的id。

思路:
这道题就是用heap做就行。

代码:



public class TopKVote {

    class Vote{
        int id;
        int timestamp;

        public Vote(int id, int timestamp){
            this.id = id;
            this.timestamp = timestamp;
        }
    }

    class Pair{
        int id;
        int count;
        public Pair(int id, int count){
            this.id = id;
            this.count = count;
        }
    }

    public List<Integer> getTopKVote(Vote[] votes, int deadline, int k){
        List<Integer> rst = new ArrayList<>();
        if(votes == null || votes.length == 0){
            return rst;
        }
        Map<Integer, Integer> count = new HashMap<>();
        for(int i = 0; i <= votes.length - 1; i++){
            Vote vote = votes[i];
            if(vote.timestamp <= deadline){
                if(count.containsKey(vote.id)){
                    count.put(vote.id, count.get(vote.id) + 1);
                }
                else{
                    count.put(vote.id, 1);
                }
            }
        }
        PriorityQueue<Pair> pq = new PriorityQueue<>(new Comparator<Pair>() {
            @Override            public int compare(Pair p1, Pair p2) {
                return p2.count - p1.count;
            }
        });

        for(int id : count.keySet()){
            pq.offer(new Pair(id, count.get(id)));
        }

        for(int i = 0; i <= k - 1; i++){
            if(!pq.isEmpty()){
                rst.add(pq.poll().id);
            }
        }
        return rst;
    }

}



Comments

Popular Posts