378. Kth Smallest Element in a Sorted Matrix

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了378. Kth Smallest Element in a Sorted Matrix相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 378. Kth Smallest Element in a Sorted Matrix

378. 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

Leetcode378. Kth Smallest Element in a Sorted Matrix