# Java heap klog(k)

• Similar to Find K Pairs with Smallest Sums.

``````public class Solution {
public int kthSmallest(final int[][] matrix, int k) {
int c = 0;
PriorityQueue<int[]> queue = new PriorityQueue<>(
k, (o1, o2) -> matrix[o1[0]][o1[1]] - matrix[o2[0]][o2[1]]);
queue.offer(new int[] {0, 0});
while (true) {
int[] pair = queue.poll();
if (++c == k) {
return matrix[pair[0]][pair[1]];
}
if (pair[0] == 0 && pair[1] + 1 < matrix[0].length) {
queue.offer(new int[] {0, pair[1] + 1});
}
if (pair[0] + 1 < matrix.length) {
queue.offer(new int[] {pair[0] + 1, pair[1]});
}
}
}
}``````

• ``````(o1, o2) -> matrix[o1[0]][o1[1]] - matrix[o2[0]][o2[1]])
``````

I wonder how this work as parameter of Comparator?
What does "->" means?

• @EncoreSummer said in Java heap klog(k):

``````(o1, o2) -> matrix[o1[0]][o1[1]] - matrix[o2[0]][o2[1]])
``````

I wonder how this work as parameter of Comparator?
What does "->" means?

This is a Lambda expression, a new feature introduced in Java 8. Here is a tutorial from Oracle.

• @munsteur thx~Got it!

• @munsteur i think the time complexity is mlogk or nlogk depending the height or width of the matrix. Whichever one is smaller

• @hwhong1129 i think you are right

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