Solution for leetcode 215
https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue();
for(int num : nums){
pq.offer(num);
if(pq.size() > k){
pq.poll();
}
}
return pq.poll();
}
}
Solution for leetcode 378
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
(another solution uses binary search)
note: The order matters for inserting into the priority queue. We need to pay attention to the special characteristics of the matrix (the element on the right and on the bottom are larger)
class Solution {
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[0] - b[0]);
pq.offer(new int[]{matrix[0][0],0,0});
int row = matrix.length;
int col = matrix[0].length;
boolean[][] visited = new boolean[row][col];
int count = 0;
while(count < k - 1){
count++;
int[] cur = pq.poll();
int x = cur[1];
int y = cur[2];
if(x + 1 < row && visited[x+1][y] == false){
visited[x + 1][y] = true;
pq.offer(new int[]{matrix[x + 1][y], x + 1, y});
}
if(y + 1 < col && visited[x][y+1] == false){
visited[x][y+1] = true;
pq.offer(new int[]{matrix[x][y + 1], x, y + 1});
}
}
return pq.poll()[0];
}
}