LC 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

Posted feiief

tags:

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

link

技术图片

 

 

class Solution {
public:
    struct Comp{
        bool operator()(vector<int>& v1, vector<int>& v2){
            return v1[0]+v1[1]>v2[0]+v2[1];
        }
    };
    
    int kthSmallest(vector<vector<int>>& mat, int k) {
        vector<int> sum=mat[0];
        int m=mat.size();
        for(int i=1;i<m;i++){
            sum=helper(sum,mat[i]);
        }
        return sum[k-1];
    }
    
    vector<int> helper(vector<int>& num1, vector<int>& num2){
        priority_queue<vector<int>, vector<vector<int>>, Comp> pq; 
        for(int i=0;i<num2.size();i++){
            pq.push({num2[i],num1[0],0});
        }
        vector<int> res;
        while(!pq.empty()){
            auto cur=pq.top();
            pq.pop();
            res.push_back(cur[0]+cur[1]);
            if(res.size()==200) break;
            if(cur[2]<num1.size()-1){
                pq.push({cur[0],num1[cur[2]+1],cur[2]+1});
            }
        }
        return res;
    }
};

 

以上是关于LC 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows的主要内容,如果未能解决你的问题,请参考以下文章

[LC] 287. Find the Duplicate Number

[LeetCode in Python] 5403 (H) find the kth smallest sum of a matrix with sorted rows 有序矩阵中的第 k 个最小数组

[LC] 230. Kth Smallest Element in a BST

[LC] 215. Kth Largest Element in an Array

The kth great number

[LC] 1102. Path With Maximum Minimum Value