题解 | #字符串出现次数的TopK问题#

字符串出现次数的TopK问题

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

package suanfa.string;

import java.util.*;

public class TopKstrings {

public static void main(String[] args) {

    String[] s = new String[]{"a", "b", "a"};

    List<MyNode> list = topKstrings(s, 2);

}

public static List<MyNode> topKstrings(String[] strings, int k) {

    Map<String, Integer> map = new HashMap<>();

    for (int i = 0; i < strings.length; i++) {
        map.put(strings[i], map.getOrDefault(strings[i], 0) + 1);
    }


    PriorityQueue<MyNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.num));

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        MyNode node = new MyNode(entry.getKey(), entry.getValue());
        if (queue.size() < k) {
            queue.offer(node);
        } else {
            MyNode tmp = queue.peek();
            if (tmp.num < node.num) {
                queue.poll();
                queue.offer(node);
            }
        }
    }
    List<MyNode> list = new ArrayList<>();

    while (queue.size() > 0) {
        list.add(queue.poll());
    }
    return list;
}


static class MyNode {
    String val;
    Integer num;

    MyNode(String val, int num) {
        this.num = num;
        this.val = val;
    }
}

}

全部评论

相关推荐

10-28 10:48
已编辑
门头沟学院 Java
孩子我想要offer:发笔试后还没笔试把我挂了,然后邮箱一直让我测评没测,后面不知道干嘛又给我捞起来下轮笔试,做完测评笔试又挂了😅
点赞 评论 收藏
分享
11-28 16:13
门头沟学院 Java
程序员小白条:年底了,都差不多了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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