Java Solution using PriorityQueue


  • 0
    M
    public List<Integer> topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> count = new HashMap<Integer,Integer>();
        
        for(Integer i : nums)
           if(!count.containsKey(i))
             count.put(i,1);
           else count.put(i,count.get(i)+1);
        
       PriorityQueue<Map.Entry<Integer,Integer>> pq = new PriorityQueue(new Comparator<Map.Entry<Integer,Integer>>() {
         @Override 
      public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
    			return o2.getValue()-o1.getValue();
    		}
    	});
    	
    	 Iterator it = count.entrySet().iterator();
          while(it.hasNext())
    	       pq.add((Map.Entry<Integer, Integer>) it.next()); 
    	
    	ArrayList<Integer> list = new ArrayList<Integer>();
    	
    	for(int i = 0; i < k; i++)
    	 list.add(pq.poll().getKey());
    	 return list;
    	 }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.