Search code examples
javalambda

Java lambda expression? how does this interprete?


class Solution {
    public int[] topKFrequent(int[] nums, int k) {

        if (k == nums.length) {
            return nums;
        }
 
        Map<Integer, Integer> count = new HashMap();
        for (int n: nums) {
          count.put(n, count.getOrDefault(n, 0) + 1);
        }

        Queue<Integer> heap = new PriorityQueue<>(
        (n1, n2) -> count.get(n1) - count.get(n2));

        for (int n: count.keySet()) {
          heap.add(n);
          if (heap.size() > k) heap.poll();    
        }

        int[] top = new int[k];
        for(int i = k - 1; i >= 0; --i) {
            top[i] = heap.poll();
        }
        return top;
    }
}

so this is answer to one of leetcode problem to find top k frequent element.

Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]

how does (n1, n2) -> count.get(n1) - count.get(n2) be written if it's not for shorten version?


Solution

  • You're using the PriorityQueue constructor that takes a Comparator as argument. The aim is to prioritize things as follows: If it has a smaller 'count' value, then it should come earlier in the queue (be higher prio).

    I guess in old java you could do:

    Queue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
      public int compare(Integer n1, Integer n2) {
        return count.get(n1) - count.get(n2);
      }
    });
    

    The return value is interpreted as follows: If negative, that means n1 comes before n2. If positive, n1 comes after. If 0 they are equal or at least comparatively at the same 'level'. It doesn't matter what negative number you pass. a - b is a cheesy way to do 'a comes before b if a is smaller', and can be dangerous if you have very large numbers - presumably that doesn't apply here.

    The better way to write this would have been:

    new PriorityQueue<>(Comparator.comparingInt(count::get));
    

    which more clearly states what you're trying to do, which is, prioritize on the result of invoking count.get(), passing as argument the thing in the queue.