首页 > 其他 > 详细

Kth Smallest Element in a Sorted Matrix -- LeetCode

时间:2016-08-19 09:50:50      阅读:185      评论:0      收藏:0      [点我收藏+]

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.

思路:将第一列的所有数(若数量大于k,则只取前k个数)放入一个数组,构建最小堆。将堆顶的数pop出来,然后将该数所在矩阵的那一行的下一个数放入堆中。该过程进行k-1次。之后堆顶的数就是第k小的数字。因此要判断堆顶的数在矩阵中的位置,因此实际放入堆中的是tuple(值,所在行数,所在列数)。复杂度O(klogm),其中m=min(行数, k)。

 1 class Solution {
 2 public:
 3     int kthSmallest(vector<vector<int>>& matrix, int k) {
 4         //tuple(val, row, col)
 5         vector<tuple<int, int, int> > heap;
 6         for (int i = 0; i < std::min((int)matrix.size(), k); i++)
 7             heap.push_back(make_tuple(matrix[i][0], i, 0));
 8         std::make_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
 9         for (int i = 0; i < k - 1; i++) {
10             std::pop_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
11             tuple<int, int, int> top = heap.back();
12             heap.pop_back();
13             int row = get<1>(top);
14             int col = get<2>(top);
15             if (col < matrix[row].size() - 1)
16                 heap.push_back(make_tuple(matrix[row][col + 1], row, col + 1));
17             std::push_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
18         }
19         return get<0>(heap.front());
20     }
21 };

 

Kth Smallest Element in a Sorted Matrix -- LeetCode

原文:http://www.cnblogs.com/fenshen371/p/5786185.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!