https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
Example 1:
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
kth smallest find krne ke lea
Step 1. add all the elements in pq
Step 2. remove til k-1
Step 3. pq ke peek pr smallest hoga
package pep.Day66;
import java.util.PriorityQueue;
import java.util.Queue;
public class LeetCode_378_Kth_Smallest_Element_in_Sorted_Matrix {
public static void main(String[] args) {
int[][] matrix = {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}};
int k = 8;
System.out.println(kthSmallest(matrix, k));
}
public static int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for(int i = 0;i<matrix.length;i++){
for(int j = 0; j<matrix[0].length;j++){
heap.add(matrix[i][j]);
}
}
int i = 1;
while(i<k){
heap.poll();
i++;
}
return heap.poll();
}
}
No comments:
Post a Comment