Back
Featured image of post You hava my word now

You hava my word now

Find my frequent word

Find the Kth-frequency word

这是5.19 的 692. 前K个高频单词

用哈希表 + 排序, HashMap记录次数 , 然后从大到小排列

public static List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        List<String> ans = new ArrayList<>();

        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            ans.add(entry.getKey());
        }

        Collections.sort(ans, new Comparator<String>() {
            //compare>0则大在前 <0则大在后
            //compareTo 比较两个str
            @Override
            public int compare(String o1, String o2) {
                return map.get(o1).equals(map.get(o2)) ? o1.compareTo(o2) : map.get(o2) - map.get(o1);
            }
        });

        return ans.subList(0, k);
}

用 哈希表 + java pq , 最小堆去除

public static List<String> topKFrequent(String[] words, int k) {
        List<String> ans = new ArrayList<>();
        Map<String, Integer> map = new HashMap<>();
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {//同样利用Comparator 进行比较
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().equals(o2.getValue()) ? o2.getKey().compareTo(o1.getKey()) : o1.getValue() - o2.getValue();
            }
        });

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            pq.offer(entry);
            if (pq.size() > k) {
                pq.poll();
            }
        }

        while (!pq.isEmpty()) {
            ans.add(pq.poll().getKey());
        }
    
        Collections.reverse(ans);//逆序
        return ans;
    }
Welcome to the world of Minezeratul