当前位置:   article > 正文

Leecode刷题笔记——378. 有序矩阵中第K小的元素_leeetcode378 python

leeetcode378 python

在这里插入图片描述
思路如下:
1、查找第k小的元素,考虑使用优先队列PriorityQueue
2、需要注意,PriorityQueue没有poll(),添加元素要使用add()方法

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int m=matrix.length;
        int n=matrix[0].length;
        PriorityQueue<Integer> queue=new PriorityQueue<>();
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                queue.add(matrix[i][j]);
            }
        }
        int res=-1;
        while(k>0){
            res=queue.poll();
            k--;
        }
        return res;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

原题地址:
378. 有序矩阵中第K小的元素

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/982663
推荐阅读
相关标签
  

闽ICP备14008679号