每天一道算法题19

给定一个由字符串组成的数组String[] strs, 给定一个正数K,返回词频最大的前K个字符串,假设答案是唯一的

解答:
构建一个小跟堆,大小就是K。
比如当前词频为
a 1
b 1
c 2
d 2

将a,b 压入堆,然后此时c,发现小根堆的堆顶的词频只有1,所以弹出,将c压入,然后到d,发现d的词频又比队顶a的词频高,所以又弹出堆顶,将d入堆

public class Node {
    public String str;
    public int times;

    public Node(String s, int t) {
        this.str = s;
        this.times = t;
    }
}

public class Comparator implements Comparator<Node> {
    @Override
    public int compare(Node o1, Node o2) {
        return o1.times - o2.times;
    }
}

public static void printTopKAndRank(String[] arr, int topK) {
    if (arr == null || arr.length == 0 || topK < 1 || topK > arr.length) {
        return;
    }

    HashMap<String, Integer>map = new HashMap<>();
    for (String st : arr) {
        if (!map.contains(str)) {
            map.put(str, 1);
        } else {
            map.put(str, map.get(str) + 1);
        }
    }

    PriorityQueue heap = new PriorityQueue<>(new NodeComparator());
    for(Entry<String, Integer> node : map.entrySet()) {
        Node cur = new Node(node.getKey(), node.getValue());
        if (heap.size() < topK) {
            heap.add(cur);
        } else {
            if (heap.peek().times < cur.times) {
                heap.poll();
                heap.add(cur);
            }
        }
    }

    while(!heap.isEmpty()) {
        System.out.print(heap.peek().str);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容