标签:
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