378. Kth Smallest Element in a Sorted Matrix

来源:互联网 发布:数据库不能附加 编辑:程序博客网 时间:2024/06/05 12:41

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.


//使用vector保存matrix中的元素,对vector排序,结果返回vector中的第k-1个元素。class Solution {public:int kthSmallest(vector<vector<int>>& matrix, int k) {int row, column;vector<int> vec;row = matrix.size();column = matrix[0].size();vec.reserve(row*column);for (vector<vector<int>>::iterator i = matrix.begin(); i != matrix.end(); ++i){for (vector<int>::iterator j = i->begin(); j != i->end(); ++j)vec.push_back(*j);}sort(vec.begin(),vec.end());return vec.at(k-1);}};