[LeetCode]378. Kth Smallest Element in a Sorted Matrix

最大堆

Posted by JinFei on December 27, 2019

题目描述

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.

Example1:

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

Note:

  1. You may assume k is always valid, 1 ≤ k ≤ n^2.

最大堆解题思路

  • 这道题让我们求有序矩阵中第K小的元素,这道题的难点在于数组并不是蛇形有序的,意思是当前行的最后一个元素并不一定会小于下一行的首元素,
  • 所以我们并不能直接定位第K小的元素,所以只能另辟蹊径。先来看一种利用堆的方法,我们使用一个最大堆,然后遍历数组每一个元素,将其加入堆,
  • 根据最大堆的性质,大的元素会排到最前面,然后我们看当前堆中的元素个数是否大于k,大于的话就将首元素去掉,循环结束后我们返回堆中的首元素即为所求:
  • 记住priority_queue的使用,往堆里插入一个值可以用方法emplace

C++代码

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        priority_queue<int> q;
        for(int i = 0; i < matrix.size(); i++){
            for(int j = 0; j < matrix[0].size(); j++){
                q.emplace(matrix[i][j]);
                if(q.size() > k){
                    q.pop();
                }
            }
        }
        return q.top();
    }
};