码迷,mamicode.com
首页 > 其他好文 > 详细

378. Kth Smallest Element in a Sorted Matrix

时间:2017-10-24 16:07:33      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:matrix   col   order   logs   pre   priority   第k小   asc   amp   

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.

Example:

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

return 13.

 

Note: 
You may assume k is always valid, 1 ≤ k ≤ n2.

题目含义:给定一个升序的矩阵,找到第k小的元素

方法一:使用优先级队列

 1     public int kthSmallest(int[][] matrix, int k) {
 2         PriorityQueue<Integer> pq = new PriorityQueue<>();
 3         if (matrix.length == 0) return Integer.MAX_VALUE;
 4         for (int i = 0; i < matrix.length; i++) {
 5             for (int j = 0; j < matrix[0].length; j++) {
 6                 pq.add(matrix[i][j]);
 7             }
 8         }
 9         int i = 0;
10         while (i < k - 1) {
11             if (!pq.isEmpty()) pq.poll();
12             i++;
13         }
14         if (!pq.isEmpty()) return pq.poll();
15         return Integer.MAX_VALUE;        
16     }

 

378. Kth Smallest Element in a Sorted Matrix

标签:matrix   col   order   logs   pre   priority   第k小   asc   amp   

原文地址:http://www.cnblogs.com/wzj4858/p/7723700.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!