GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — SolvedAlgorithm/Sorting Algorithm/692.md at main · EsperErWang/SolvedAlgorithm

Expand file tree

/

692.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
32 lines (26 loc) · 1.03 KB
/

692.md

Copy path

File metadata and controls

32 lines (26 loc) · 1.03 KB
Raw
Copy raw file
Download raw file
Edit and raw actions
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;                                                        
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.