Skip to content

Latest commit

 

History

History
32 lines (26 loc) · 1.03 KB

File metadata and controls

32 lines (26 loc) · 1.03 KB
public List<String> topKFrequent(String[] words, int k) {
    Map<String, Integer> stringToFre = new HashMap<>();
    List<String> result = new ArrayList();

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

    // when pq poll out, is the less fre element,
    // so when we put it in the result, we should reverse the result,
    // so if the fre is the same, we should set the reversed alphabetical order.
    PriorityQueue<String> maxFre = new PriorityQueue<>
        ((a, b) -> (stringToFre.get(a) == stringToFre.get(b) ? 
                    b.compareTo(a) : stringToFre.get(a) - stringToFre.get(b)));

    for (String word : stringToFre.keySet()) {
        maxFre.add(word);
        if (maxFre.size() > k) {
            maxFre.poll();
        }
    }

    while (!maxFre.isEmpty()) {
        result.add(maxFre.poll());
    } 

    Collections.reverse(result);        
    return result;                                                        
}