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/451.md at main · EsperErWang/SolvedAlgorithm

Expand file tree

/

451.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
30 lines (26 loc) · 845 Bytes
/

451.md

Copy path

File metadata and controls

30 lines (26 loc) · 845 Bytes
Raw
Copy raw file
Download raw file
Edit and raw actions
public String frequencySort(String s) {
    // use array to save the char and it's frequency
    int[] charToFre = new int[256];
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        charToFre[c]++;
    }

    PriorityQueue<Integer> sortResult = new PriorityQueue<>
        ((a, b) -> (charToFre[a] == charToFre[b] ? a - b : charToFre[b] - charToFre[a]));

    for (int i = 0; i < 256; i++) {
        if (charToFre[i] > 0) {
            sortResult.add(i);
        }
    }
    
    // the int should be convert to char!!!
    StringBuilder result = new StringBuilder();
    while (!sortResult.isEmpty()) {
        int i = sortResult.poll();
        for (int j = 0; j < charToFre[i]; j++) {
            result.append((char)(i));
        }
    }
    return result.toString();
}
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.