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
- leetcode378:Kth Smallest Element in a Sorted Matrix(medium)
- Leetcode378: Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix 难度:medium
- LeetCode 378. Kth Smallest Element in a Sorted Matrix (Medium)
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix
- Kth Smallest Element in a Sorted Matrix (Leetcode)二分法
- 378. Kth Smallest Element in a Sorted Matrix (二分)
- 378.leetcode Kth Smallest Element in a Sorted Matrix(medium)[堆求第K小的 ]
- Leetcode 378. Kth Smallest Element in a Sorted Matrix (Medium) (cpp)
- 378. Kth Smallest Element in a Sorted Matrix
- 【Leetcode】Kth Smallest Element in a Sorted Matrix
- 378. Kth Smallest Element in a Sorted Matrix 解题报告
- LeetCode—378. Kth Smallest Element in a Sorted Matrix
- 摇一摇
- 集合
- Thrift实战开发
- 核心动画 -- CABasicAnimation简介
- m4a音频无法seek
- leetcode378:Kth Smallest Element in a Sorted Matrix(medium)
- 8、Spring MVC 之 Handler mappings
- 如何获取spring的beans.xml的内容
- 看《从psd到html》小结
- linux内核 路由缓存表之创建
- csu 1105 NBUT1108 打怪升级
- JS横向循环滑动也可移动性切换
- 开源项目circular-progress-button源码分析
- Intent四个重要属性