Java Solution, using priorityQueue.


  • 0
    C
    public class Solution {
    	public List<Integer> topKFrequent(int[] nums, int k) {
            Map<Integer,Integer> map = new HashMap<>();
            List<Integer> result = new ArrayList<>();
            for(int n : nums) {
                if(!map.containsKey(n)) map.put(n,0);
                int size = map.get(n);
                size++;
                map.put(n,size);
            }
            Set<Map.Entry<Integer, Integer>> set = map.entrySet();
            Iterator<Map.Entry<Integer, Integer>> i = set.iterator();
            PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(set.size(),new myComparator());
            while(i.hasNext()) {
            	queue.add(i.next());
            }
            while(k>0) {
            	result.add(queue.poll().getKey());
            	k--;
            }
            return result;
        }
        
    
        
    	private class myComparator implements Comparator<Map.Entry<Integer, Integer>> {
            @Override
           public int compare(Map.Entry<Integer, Integer> p1, Map.Entry<Integer, Integer> p2) {
                if(p1.getValue() > p2.getValue()) return -1;
                else if(p1.getValue() == p2.getValue()) return 0;
                return 1;
            }
        }
    }

Log in to reply
 

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