378. Kth Smallest Element in a Sorted Matrix

来源:互联网 发布:highcharts.js 下载 编辑:程序博客网 时间:2024/04/28 02:16

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.

这道题主要是把二位矩阵变成一维矩阵,然后排序,然后取k-1为索引的数即可。
代码如下:

class Solution {public:    int kthSmallest(vector<vector<int>>& matrix, int k) {      int r=matrix.size();      int l=matrix[0].size();      vector<int>h;      for(int i=0;i<r;i++){          for(int j=0;j<l;j++){              h.push_back(matrix[i][j]);          }      }      sort(h.begin(),h.end());      return h[k-1];    }};
原创粉丝点击