jaduuu

 avatar
bruteCoder
java
a year ago
1.3 kB
4
Indexable
class Solution {
    public static ArrayList<ArrayList<Integer>> kTop(int[] arr, int N, int K) {
        // code here
        HashMap<Integer,Integer> hmap = new HashMap<>();
        
        ArrayList<ArrayList<Integer>> out = new ArrayList<>();
        
        for(int el : arr){
            hmap.put(el,hmap.getOrDefault(el,0)+1);
            
        PriorityQueue<Pair> pq = new PriorityQueue<>(new customComparator());
            for(Map.Entry<Integer,Integer> entry : hmap.entrySet()){
                pq.offer(new Pair(entry.getKey(),entry.getValue()));
            }
            
           ArrayList<Integer> flist = new ArrayList<>();
           while(!pq.isEmpty() && flist.size()<K){
               flist.add(pq.poll().val);
           }
           
           out.add(flist);
        }
        
        return out;
        
        
        
    }
  
}
 class Pair{
     int val;
     int freq;
     
     public Pair(int val, int freq){
         this.val = val;
         this.freq = freq;
     }
     
}


class customComparator implements Comparator<Pair> 
{
    public int compare(Pair p1, Pair p2){
        int frq1 = p1.freq;
        int frq2 = p2.freq;
        
        if(frq1 == frq2) return p1.val - p2.val;
        return frq2-frq1;
    }
}
        
        
Editor is loading...
Leave a Comment