LeetCode - 692 - media - TopKFrequentWords

resumen:

1.hashmap 

2. min montón 

3. orden alfabético (diccionario orden), en Java, "abc" .compareTo "ab", es relativamente lexicográfico implementado

4. Necesitamos sobrescribimos Comparador

package com.odyssey.app.algorithm.lc.trie;

import java.util.*;

/**
 * 692
 * medium
 * https://leetcode.com/problems/top-k-frequent-words/
 *
 * Given a non-empty list of words, return the k most frequent elements.
 *
 * Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
 *
 * Example 1:
 * Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
 * Output: ["i", "love"]
 * Explanation: "i" and "love" are the two most frequent words.
 *     Note that "i" comes before "love" due to a lower alphabetical order.
 * Example 2:
 * Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
 * Output: ["the", "is", "sunny", "ady"]
 * Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
 *     with the number of occurrence being 4, 3, 2 and 1 respectively.
 * Note:
 * You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
 * Input words contain only lowercase letters.
 * Follow up:
 * Try to solve it in O(n log k) time and O(n) extra space.
 *
 *
 * @author Dingsheng Huang
 * @date 2020/3/29 0:22
 */
public class TopKFrequentWords {

    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> countMap = new HashMap<>();
        // frequent count
        count(countMap, words);
        // min heap , override compare
        PriorityQueue<Map.Entry<String, Integer>> minHeap = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if (o1.getValue() > o2.getValue()) {
                    return 1;
                } else if (o1.getValue() < o2.getValue()) {
                    return -1;
                } else {
                    return -(o1.getKey().compareTo(o2.getKey()));
                }
            }
        });

        // get top k frequent words
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            minHeap.add(entry);
            if (minHeap.size() > k) {
                minHeap.remove();
            }
        }

        // sort,  we get item from min heap one by one,  then we get the sorted list !
        List<String> result = new ArrayList<>();
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>();
        while (!minHeap.isEmpty()) {
            // equal minHeap.poll()
            entryList.add(minHeap.peek());
            minHeap.remove();
        }
        for (int i = entryList.size() - 1; i >= 0; i--) {
            result.add(entryList.get(i).getKey());
        }
        return result;
    }

    private void count(Map<String, Integer> map, String[] words) {
        for (String word : words) {
            if (map.containsKey(word)) {
                map.put(word, map.get(word) + 1);
            } else {
                map.put(word, 1);
            }
        }
    }
}

 

Ha publicado 195 artículos originales · ganado elogios 26 · vistas 40000 +

Supongo que te gusta

Origin blog.csdn.net/huangdingsheng/article/details/105172635
Recomendado
Clasificación