Kth Smallest Element in a Sorted Matrix

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();
  }
}

 

https://stackoverflow.com/questions/11003155/change-priorityqueue-to-max-priorityqueue

 

 

https://stackoverflow.com/questions/683041/how-do-i-use-a-priorityqueue

======================================
PriorityQueue<Integer> pq = new PriorityQueue<Integer> (
  new Comparator<Integer> () {
    public int compare(Integer a, Integer b) {
       return b - a;
    }
  }
);

======================================

 

 

 

Here is the output:

short

medium

very long indeed


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.)

 

posted @ 2023-01-29 03:31  叶漾知  阅读(29)  评论(0)    收藏  举报