LeetCode

来源:互联网 发布:杭州半包价格2017 知乎 编辑:程序博客网 时间:2024/05/17 01:02

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小的数是多少。

逐次取出最小的数字来找出最终结果。将第一行元素存入小根堆,最小元素必定在堆顶(matrix[0][0]),然后删除堆顶数字并用它同列的下一数字代替,这样当前最小的数字依然在堆顶,遍历k次后即可得到第k小的数字。由于需要记录数字的坐标,这里用结构体包含了数字值和两个坐标。

class Solution {    public:    struct num {        int x, y;        int val;        num(int v, int xx, int yy):val(v), x(xx), y(yy) {}            };    struct cmp {          bool operator() (const num& n1, const num& n2) {              return n1.val > n2.val;          }      };         int kthSmallest(vector<vector<int>>& matrix, int k) {        priority_queue<num, vector<num>, cmp> pq;        for (int i = 0; i < matrix[0].size(); ++i) {            pq.push(num(matrix[0][i], 0, i));        }        for (int i = 0; i < k - 1; ++i) {            num cur = pq.top();            pq.pop();            int xx = cur.x + 1;            int yy = cur.y;            if (xx == matrix.size()) continue;            pq.push(num(matrix[xx][yy], xx, yy));        }        return pq.top().val;    }    };
评论区还有种做法,用二分查找。在二分查找循环中,统计矩阵中小于等于中间值的数字个数,拿它和k比较来确定第k小的数字在前半部分还是后半部分

class Solution{public:int kthSmallest(vector<vector<int>>& matrix, int k){int n = matrix.size();int le = matrix[0][0], ri = matrix[n - 1][n - 1];int mid = 0;while (le < ri){mid = le + (ri-le)/2;int num = 0;for (int i = 0; i < n; i++){int pos = upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();num += pos;}if (num < k){le = mid + 1;}else{ri = mid;}}return le;}};


原创粉丝点击