378. 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.
class Solution { public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int m = matrix[0].length; PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>((a, b) -> a.val - b.val); for(int j = 0; j < m; j++) pq.offer(new Tuple(0, j, matrix[0][j])); for(int i = 0; i < k-1; i++) { Tuple t = pq.poll(); if(t.x == n-1) continue; pq.offer(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y])); } return pq.poll().val; } } class Tuple { int x, y, val; public Tuple (int x, int y, int val) { this.x = x; this.y = y; this.val = val; } }
posted on 2018-11-06 08:39 猪猪🐷 阅读(96) 评论(0) 收藏 举报
浙公网安备 33010602011771号