class Solution { // 14 ms, faster than 55.67%
public int kthSmallest( int[][] matrix, int k ) {
int m = matrix.length, n = matrix[0].length ; // For general, the matrix need not be a square
PriorityQueue<Integer> maxHeap = new PriorityQueue<>( (o1, o2) -> Integer.compare(o2, o1) ) ;
for ( int r = 0 ; r < m ; ++r ) {
for ( int c = 0 ; c < n ; ++c ) {
maxHeap.offer( matrix[r][c] ) ;
if ( maxHeap.size() > k ) maxHeap.poll() ; // maxHeap() 从大到小排,排到第k个,队顶最大弹出;新元素加入;
}
}
return maxHeap.poll();
}
}
You can use lambda expression since Java 8.
The following code will print 10, the larger.
// There is overflow problem when using simple lambda as comparator, as pointed out by Фима Гирин.
// PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
PriorityQueue<Integer> pq =new PriorityQueue<>((x, y) -> Integer.compare(y, x));
pq.add(10);
pq.add(5);
System.out.println(pq.peek());
The lambda function will take two Integers as input parameters, subtract them from each other, and return the arithmetic result. The lambda function implements the Functional Interface, Comparator<T>
. (This is used in place, as opposed to an anonymous class or a discrete implementation.)
标签:pq,matrix,int,maxHeap,PriorityQueue,Smallest,Kth,Sorted,lambda From: https://www.cnblogs.com/YeYangzhi/p/17071637.html