LeetCode-Kth Smallest Element in a Sorted Matrix
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
Solution:
1 public class Solution { 2 public class ValuePair { 3 int val; 4 int x; 5 int y; 6 public ValuePair(int v, int i, int j){ 7 val = v; 8 x = i; 9 y = j; 10 } 11 } 12 public int kthSmallest(int[][] matrix, int k) { 13 if (matrix.length==0 || matrix[0].length==0) return -1; 14 15 PriorityQueue<ValuePair> q = new PriorityQueue<ValuePair>((a,b) -> (a.val-b.val)); 16 17 for (int i=0;i<matrix.length;i++){ 18 ValuePair p = new ValuePair(matrix[i][0],i,0); 19 q.add(p); 20 } 21 22 ValuePair peek = null; 23 for (int i=0;i<k-1;i++){ 24 peek = q.poll(); 25 peek.y++; 26 if (peek.y<matrix[0].length){ 27 peek.val = matrix[peek.x][peek.y]; 28 q.add(peek); 29 } 30 } 31 peek = q.poll(); 32 return peek.val; 33 } 34 }