赞
踩
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
vector<int> ans;
for(int i=0;i<matrix.size();i++)
for(int j=0;j<matrix[0].size();j++)
ans.emplace_back(matrix[i][j]);
sort(ans.begin(),ans.end());
return ans[k-1];
}
};
<val,x,y>
class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { struct point { int val, x, y; point(int val, int x, int y) : val(val), x(x), y(y) {} bool operator> (const point& a) const { return this->val > a.val; } }; //创建优先队列 存入每行头地址 priority_queue<point, vector<point>, greater<point>> que; int n = matrix.size(); for (int i = 0; i < n; i++) que.emplace(matrix[i][0], i, 0); //每次压入当前栈顶的右边元素 若当前元素是最右边元素则不压入 for (int i = 0; i < k - 1; i++) { point now = que.top(); que.pop(); if (now.y != n - 1) que.emplace(matrix[now.x][now.y + 1], now.x, now.y + 1); } return que.top().val; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。