资讯专栏INFORMATION COLUMN

378. Kth Smallest Element in a Sorted Matrix

makeFoxPlay / 2155人阅读

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.

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13
public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        PriorityQueue pq = new PriorityQueue<>(new Comparator(){
            public int compare(int[] a, int[] b){
                return a[2] - b[2];
            }
        });
        
        int n = matrix.length;
        // add first row
        for(int i=0; i< n; i++){
            pq.offer(new int[]{0, i, matrix[0][i]});
        }
        
        for(int i=0; i
public class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int m = matrix.length, n = matrix[0].length;
        int lo = matrix[0][0],  hi = matrix[m-1][n-1];
        while(lo < hi){
            int mid = lo + (hi-lo)/2;
            int count = 0, j = n -1;
            for(int i=0; i=0 && matrix[i][j] > mid) j--;
                // count those <= mid
                count += j+1;
            }
            // if count < k, the number is smaller
            if(count < k) lo = mid+1;
            else hi = mid;
        }
        return lo;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67070.html

相关文章

  • [LeetCode] 378. Kth Smallest Element in a Sorted M

    摘要:先放一行,或一列把堆顶的最小元素取出来,取次,如果该有下一行下一列的,放入堆中最小的个元素已经在上面的循环被完了,下一个堆顶元素就是 Problem Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in...

    Shihira 评论0 收藏0
  • 378. Kth Smallest Element in a Sorted Matrix

    摘要:复杂度是,其中。这做法和异曲同工。看了网上给的解法,没有二分,二分的是结果。每次找到一个,然后求比它小的元素的个数,根据个数大于还是小于来二分。参考算的时候可以优化 378. Kth Smallest Element in a Sorted Matrix 题目链接:https://leetcode.com/problems... 求矩阵里面第k小的数,首先比较容易想到的是用heap来做...

    Y3G 评论0 收藏0
  • leetcode378. Kth Smallest Element in a Sorted Matr

    摘要:因此我们可以采用部分元素堆排序即可。即我们每次只需要可能构成第个元素的值进行堆排序就可以了。 题目要求 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...

    dailybird 评论0 收藏0
  • [LintCode] Kth Smallest Number in Sorted Matrix

    Problem Find the kth smallest number in at row and column sorted matrix. Example Given k = 4 and a matrix: [ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9], ] return 5 Challenge O(k log n), n is the maximal n...

    mgckid 评论0 收藏0
  • [Leetcode] Kth Smallest Element in a BST 二叉搜索树第k小节

    摘要:中序遍历复杂度时间空间思路因为左节点小于根节点小于右节点,二叉搜索树的一个特性就是中序遍历的结果就是树内节点从小到大顺序输出的结果。这里采用迭代形式,我们就可以在找到第小节点时马上退出。这样我们就可以用二叉树搜索的方法来解决这个问题了。 Kth Smallest Element in a BST Given a binary search tree, write a function...

    Dean 评论0 收藏0

发表评论

0条评论

makeFoxPlay

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<