leetcode_middle_19_378. Kth Smallest Element in a Sorted Matrix
来源:互联网 发布:网络培训个人研修计划 编辑:程序博客网 时间:2024/06/06 15:49
题意:
给一个二维数组,表示一个n*n矩阵,每个行和列都升序,找出第k小的数
分析:
一直找规律,写代码,出错,发现规律出错,再改再写再错...反复多次没法,还是用优先队列吧。只要不停地动态更新k大小的优先队列,就能够选出前k个小的,取出队列头就能得到第k大的。
public class Solution { public int kthSmallest(int[][] matrix, int k) { PriorityQueue<Integer> pq= new PriorityQueue(k, Collections.reverseOrder()); //从小到大 for(int i=0;i < matrix.length;i++){ for(int j=0;j < matrix.length;j++){ if(pq.size() < k) pq.add(matrix[i][j]); else{ if(pq.peek() > matrix[i][j]){ //有更小的就更新 pq.poll(); pq.offer(matrix[i][j]); } } } } return pq.poll(); }}
0 0
- leetcode_middle_19_378. 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
- 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
- Leetcode 378. Kth Smallest Element in a Sorted Matrix
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- 【leetcode】378. Kth Smallest Element in a Sorted Matrix
- LeetCode[378] Kth Smallest Element in a Sorted Matrix
- LeetCode:378 Kth Smallest Element in a Sorted Matrix
- leetcode之 Kth Smallest Element in a Sorted Matrix
- 回文字符串
- [leetcode]--260. Single Number III
- R语言利用wordcloud2绘制词云
- redis使用介绍
- runtime error可能的原因
- leetcode_middle_19_378. Kth Smallest Element in a Sorted Matrix
- 九度 oj 题目1104:整除问题
- Shibboleth SSO 登录流程
- leetcode 49. Group Anagrams
- zen-coding的使用
- 连接linux服务器的软件
- JAVASE基础-day07(面向对象)
- Unity跑酷扭曲shader
- HTML 中不常用但是很有用的标签