首页 > 其他 > 详细

Leetcode 378. Kth Smallest Element in a Sorted Matrix

时间:2016-08-05 10:11:24      阅读:187      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!