首页 > 其他 > 详细

378. Kth Smallest Element in a Sorted Matrix

时间:2019-10-28 01:21:05      阅读:115      评论:0      收藏:0      [点我收藏+]
import java.util.*

/**
 * 378. Kth Smallest Element in a Sorted Matrix
 * https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/
 *
 * 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.
 * */
class Solution {
    fun kthSmallest(matrix: Array<IntArray>, k: Int): Int {
        //set the maximum heap
        val queue = PriorityQueue<Int>() { a, b -> b - a }
        for (i in 0 until matrix.size) {
            for (j in 0 until matrix[i].size) {
                queue.offer(matrix[i][j])
                if (queue.size > k) {
                    //if size bigger than k, pop the head
                    queue.poll()
                }
            }
        }
        return queue.peek()
    }
}

 

378. Kth Smallest Element in a Sorted Matrix

原文:https://www.cnblogs.com/johnnyzhao/p/11749992.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!