题目:
在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。
样例:
样例
给出 k = 4 和一个排序矩阵:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
返回 5。
思路:
将矩阵中每个元素放入一个向量中,然后对向量元素进行排序,然后取出第k大的数。
参考答案:
class Solution {
public:
/*
* @param matrix: a matrix of integers
* @param k: An integer
* @return: the kth smallest number in the matrix
*/
int kthSmallest(vector<vector<int>> matrix, int k) {
// write your code here
if(matrix.empty()) return 0;
int m = matrix.size();
int n = matrix[0].size();
vector<int> res;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
res.push_back(matrix[i][j]);
}
}
sort(res.begin(),res.end());
return res[k-1];
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。