fork download
  1. import java.util.*;
  2. import java.util.concurrent.BlockingQueue;
  3. import java.util.concurrent.LinkedBlockingQueue;
  4. import java.math.*;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.lang.*;
  8. class Node{
  9. int val;
  10. int freq;
  11. Node(int val, int freq){
  12. this.val = val;
  13. this.freq = freq;
  14. }
  15. }
  16. class Solution{
  17. public static int[] itemSort(int[] items) {
  18. Map<Integer, Integer> itemMap = new HashMap<>();
  19. for(int item : items)
  20. itemMap.put(item, itemMap.getOrDefault(item, 0)+1);
  21.  
  22. PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>() {
  23. public int compare(Node n1, Node n2) {
  24. int cmp = n1.freq - n2.freq;
  25. if(cmp != 0)
  26. return cmp;
  27. return n1.val - n2.val;
  28. }
  29. });
  30.  
  31. for(Map.Entry<Integer, Integer> m : itemMap.entrySet()) {
  32. pq.offer(new Node(m.getKey(), m.getValue()));
  33. }
  34.  
  35. int n = items.length;
  36. int[] res = new int[n];
  37. int index = 0;
  38. while(!pq.isEmpty()) {
  39. Node node = pq.poll();
  40. int f = node.freq;
  41. while(f > 0) {
  42. res[index++] = node.val;
  43. f--;
  44. }
  45. }
  46.  
  47. return res;
  48. }
  49. // Driver code
  50. public static void main(String[] args) throws InterruptedException {
  51. int[] items = {3,1,2,2,4};
  52. System.out.println(Arrays.toString(items));
  53. System.out.println(Arrays.toString(itemSort(items)));
  54.  
  55.  
  56. int[] items2 = {8,5,5,5,5,1,1,1,4,4};
  57. System.out.println(Arrays.toString(items2));
  58. System.out.println(Arrays.toString(itemSort(items2)));
  59.  
  60. }
  61. }
Success #stdin #stdout 0.06s 51028KB
stdin
Standard input is empty
stdout
[3, 1, 2, 2, 4]
[1, 3, 4, 2, 2]
[8, 5, 5, 5, 5, 1, 1, 1, 4, 4]
[8, 4, 4, 1, 1, 1, 5, 5, 5, 5]