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

字符串出现次数的TopK问题

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

package com.hhdd.哈希;

import java.util.*;

/**
 * @Author huanghedidi
 * @Date 2022/8/23 23:07
 */
public class 字符串出现次数的TopK问题 {

    public static void main(String[] args) {
        String[][] res = topKstrings(new String[]{"abcd", "abcd", "abcd", "pwb2","abcd","pwb2","p12"}, 3);
        System.out.println(Arrays.toString(res));
    }

    /**
     * return topK string
     *
     * @param strings string字符串一维数组 strings
     * @param k       int整型 the k
     * @return string字符串二维数组
     */
    public static String[][] topKstrings(String[] strings, int k) {
        // write code here
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < strings.length; i++) {
            String tmp = strings[i];
            if (map.containsKey(tmp)) {
                map.put(tmp, map.get(tmp) + 1);
            } else {
                map.put(tmp, 1);
            }
        }
        ArrayList<Item> help = new ArrayList<>();
        for (Map.Entry<String, Integer> item : map.entrySet()) {
            Item tmp = new Item();
            tmp.times = item.getValue();
            tmp.str = item.getKey();
            help.add(tmp);
        }
        List<String[]> res = new ArrayList<>();
        PriorityQueue<Item> priorityQueue = new PriorityQueue<>(help);
        for (int i = 0; i < k; i++) {
            Item item = priorityQueue.poll();
            res.add(new String[]{item.str, item.times + ""});
        }
        String[][] ans = new String[res.size()][2];
        for (int i = 0; i < res.size(); i++) {
            ans[i] = res.get(i);
        }
        return ans;
    }

    static class Item implements Comparable<Item> {
        public String str;
        public int times;

        @Override
        public int compareTo(Item o) {
            if (this.times == o.times) {
                return str.compareTo(o.str);
            }
            return o.times - times;
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务