出现次数为topK的问题

出现次数的TopK问题

http://www.nowcoder.com/questionTerminal/fd711bdfa0e840b381d7e1b82183b3ee

用Java的小根堆进行排序

import java.util.*;


public class Solution {
    /**
     * return topK string
     * @param strings string字符串一维数组 strings
     * @param k int整型 the k
     * @return string字符串二维数组
     */
    public String[][] topKstrings (String[] strings, int k) {
        // write code here
        if(k == 0 || strings.length == 0)
            return new String[0][0];
        //统计每个数字出现的次数
        Map<String, Integer> countMap = new HashMap<>();
        for(String str : strings){
            countMap.put(str, countMap.getOrDefault(str,0)+1);
        }
        //建立大小为k的小根堆
        //w1表示要添加进来的数,w2表示堆头
       PriorityQueue<String> heap = new PriorityQueue<String>(
            (w1, w2) -> countMap.get(w1).equals(countMap.get(w2)) ?
            w2.compareTo(w1) : countMap.get(w1) - countMap.get(w2) );
        for(String str : countMap.keySet()){
            //会按照定义的去排序,跟堆头比较
            heap.offer(str);
            //poll方法是poll出堆头,把最小的去掉,再把最小的一位放在堆头
            if(heap.size() > k) heap.poll();
        }
        String[][] res = new String[k][2];
        int idx = k-1;
        while(!heap.isEmpty()){
            String temp = heap.poll();
            res[idx][0] = temp;
            res[idx][1] = countMap.get(temp) + "";
            idx--;
        }

        return res;
    }
}
全部评论

相关推荐

就在我现在公司的隔壁每天经过都唏嘘不已(就是羡慕)什么时候可以到这里上班啊
柯基在debug:从大学毕业投简历到现在了,应届的时候我都面到终面了,现在工作四年了连简历初筛都过不了了
投递莉莉丝游戏等公司8个岗位 >
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务