Shortest and simple solution using lambda expression

  • 0

    I used heap to get the top k. It's nothing special but just want to say it's very handy to use lambda here.

    public List<Integer> topKFrequent(int[] nums, int k) {
    	Map<Integer, Integer> map = new HashMap<>();
    	for (int num : nums) {
    	    map.put(num, map.getOrDefault(num, 0) + 1);
            PriorityQueue<Integer> queue = new PriorityQueue<>(k, (a, b) -> map.get(a) - map.get(b));
            for (int num : map.keySet()) {
                if (queue.size() > k) {
            return new ArrayList<Integer>(queue);

Log in to reply

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