LeetCode 378. Kth Smallest Element in a Sorted Matrix 题解(C++)

本文提供两种解决LeetCode 378题的方法:一是利用优先队列找到第k小的元素;二是通过保存矩阵第一行元素并迭代k-1次来找到答案。这两种方法均可高效解决在已排序矩阵中查找第k小元素的问题。

LeetCode 378. Kth Smallest Element in a Sorted Matrix 题解(C++)


题目描述

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

举例

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

补充

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

思路

思路1
  • 设置一个优先队列,先保存前k个元素,之后遍历矩阵,每次循环都将该元素放进队列,并从队列中出队一个元素(因为是优先队列,出队的元素是队列中的最大值),遍历完成返回队列头的元素即为所求的值。
思路2
  • 使用优先队列先保存第一行的元素及每个元素对应的位置(这里优先队列的比较函数需要重新定义),之后执行k-1次循环,每次循环都从队列中出队一个最小的元素,并取该元素在矩阵中的下一行的元素入队,若该元素处于最后一行,则不需要取元素入队,最后返回队列头的元素。

代码

代码1
class Solution 
{
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) 
    {
        priority_queue<int> queue;
        int i = 0, j = 0, t = 0;
        while (t < k)
        {
            queue.push(matrix[i][j]);
            ++j;
            if (j == matrix[0].size())
            {
                ++i;
                j = 0;
            }
            ++t;
        }
        for (; i < matrix.size(); ++i)
        {
            for (; j < matrix[0].size(); ++j)
            {
                queue.push(matrix[i][j]);
                queue.pop();
            }
            j = 0;
        }
        return queue.top();
    }
};
代码2
class Solution 
{
public:
struct comp
{
    bool operator()(const pair<int, pair<int, int>> &a, const pair<int, pair<int, int>> &b)
    {
        return a.first > b.first;
    }
};
    int kthSmallest(vector<vector<int>>& matrix, int k) 
    {
        int row = matrix.size();
        int column = matrix[0].size();
        priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, comp> queue;
        for (int i = 0; i < column; ++i)
        {
            queue.push(make_pair(matrix[0][i], make_pair(0, i)));
        }
        while (--k)
        {
            int val = queue.top().first;
            int rowTemp = queue.top().second.first;
            int columnTemp = queue.top().second.second;
            queue.pop();
            if (rowTemp != row - 1)
            {
                queue.push(make_pair(matrix[rowTemp + 1][columnTemp], make_pair(rowTemp + 1, columnTemp)));
            }
        }
        return queue.top().first;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值