leetcode378:Kth Smallest Element in a Sorted Matrix(medium)

来源:互联网 发布:盛杰影视网络课 编辑:程序博客网 时间:2024/06/03 11:26

每天能静下心来学习的时候才是最开心的时候,总是感觉被各种事情缠着,每天很忙,但回想一下好像今天也没做什么,今天开始看了深度学习框架Caffe,过几天可以总结一下,今天先总结一下leetcode第378道题目,属于比较简单的,这道题再一次让我们看到了数据结构的强大之处。

题目: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.

题意:给定一个矩阵,这个矩阵的每一行和每一列都是递增的(但不保证上一行的最后一列元素小于下一行的第一列元素,即不保证元素是递增的),现在给一个正整数k,返回这个矩阵中第k小的元素。

思路:利用优先队列,该算法分为两步:1.遍历一遍矩阵,将每个元素add到优先队列PriorityQueue中;2.从优先队列进行poll操作k次,即可将第k小的数从优先队列中取出。代码实现如下:

public class Solution {    public int kthSmallest(int[][] matrix, int k) {        PriorityQueue<Integer> dq = new PriorityQueue<Integer>();int height = matrix.length;int width = matrix[0].length;if(height <=0 || width <=0)return 0;int sum = height*width;for(int i=0;i<height;i++)for(int j=0;j<width;j++)dq.add(matrix[i][j]);while(--k>0)dq.poll();return dq.poll();    }}

1 0
原创粉丝点击