码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 378. Kth Smallest Element in a Sorted Matrix

时间:2016-08-05 10:13:26      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:

378. Kth Smallest Element in a Sorted Matrix

  • Total Accepted: 3183
  • Total Submissions: 7968
  • Difficulty: Medium

 

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: 

 

 

思路:简单粗暴,直接对所有元素升序排序后,取第k个元素。

 

代码:

 1 class Solution {
 2 public:
 3     int kthSmallest(vector<vector<int> >& matrix, int k) {
 4         priority_queue<int,vector<int>,greater<int> > pq;
 5         int n=matrix.size();
 6         for(int i=0;i<n;i++){
 7             for(int j=0;j<n;j++){
 8                 pq.push(matrix[i][j]);
 9             }
10         }
11         int res;
12         for(int i=0;i<k;i++){
13             res=pq.top();
14             pq.pop();
15         }
16         return res;
17     }
18 };

 

 

Leetcode 378. Kth Smallest Element in a Sorted Matrix

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5739997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!