LeetCode 378. Kth Smallest Element in a Sorted Matrix [heap] [java]

Source: https://leetcode.com/problems/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.

I know this problem must have some more elegant solutions, because we have some information of the matrix, but I am processing problems about heap, so I just provide a heap solution. (codes about max-heap see this)

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0378

Want to know more details of heap and heapsort, check my post:Heap and Heap-Sort algorithm.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.