【Leetcode】378. Kth Smallest Element in a Sorted Matrix(第k个大的数)(容器)

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个大的数。

解题思路:

看讨论区里直接将矩阵转化成为一维数组排序出结果,貌似比搜索还要快。

最后想练习一下容器。利用priority_queue来排序pair,每个比当前大的数可能出现在右面或者下面。

class Solution {
private:
    int map_x[2] = {1,0};
    int map_y[2] = {0,1};
    bool valid(int x, int y, int n){
        if(x>=0 && x<n && y>=0 && y<n){
            return true;
        }
        return false;
    }
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        if(k==1) return matrix[0][0];
        int n = matrix.size();
        bool maps[n][n];
        memset(maps, false, sizeof(maps));
        priority_queue<pair<int, vector<int>>, vector<pair<int, vector<int>>>, greater<pair<int, vector<int>>> > q;
        vector<int> tmp_v;
        tmp_v.push_back(0);
        tmp_v.push_back(0);
        pair<int ,vector<int>> p1;
        p1.first = matrix[0][0];
        p1.second = tmp_v;
        q.push(p1);
        maps[0][0]= true;
        int ans = matrix[0][0];
        while(k--){
            int x = q.top().second[0];
            int y = q.top().second[1];
            ans = q.top().first;
            q.pop();
            for(int k = 0;k<2;k++){
                int cor_x = map_x[k] + x;
                int cor_y = map_y[k] + y;
                if(valid(cor_x, cor_y,n) && maps[cor_x][cor_y]==false){
                    maps[cor_x][cor_y] = true;
                    vector<int> tmp_v;
                    tmp_v.push_back(cor_x);
                    tmp_v.push_back(cor_y);
                    pair<int ,vector<int>> p1;
                    p1.first = matrix[cor_x][cor_y];
                    p1.second = tmp_v;
                    q.push(p1);
                }
            } 
        }
        return ans;
    }
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值