在一个排序矩阵中找从小到大的第 k 个整数。
排序矩阵的定义为:每一行递增,每一列也递增。
样例:
给出 k = 4 和一个排序矩阵:
[
[1 ,5 ,7],
[3 ,7 ,8],
[4 ,8 ,9],
]
返回 5。
挑战 :
使用O(k log n)的方法,n为矩阵的宽度和高度中的最大值。
思路:
与接雨水II类似,利用priority_queue构建小顶堆,在符合条件的情况下将队头元素的右边和下边入队,
将队头元素出队,进行k次。
#ifndef C401_H
#define C401_H
#include<iostream>
#include<vector>
#include<queue>
#include<functional>
using namespace std;
class Solution {
public:
/*
* @param matrix: a matrix of integers
* @param k: An integer
* @return: the kth smallest number in the matrix
*/
int kthSmallest(vector<vector<int>> matrix, int k) {
// write your code here
if (matrix.empty()||k<=0)
return 0;
priority_queue<pair<int, int>,vector<pair<int, int>>, greater<pair<int, int>>> que;
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>> visited(row, vector<int>(col, 0));
que.push(make_pair(matrix[0][0], 0 * col + 0));
visited[0][0] = 1;
while (k--)
{
auto pairVal = que.top();
que.pop();
if (k == 0)
return pairVal.first;
int i = pairVal.second / col;
int j = pairVal.second%col;
if (i + 1 < row&&visited[i + 1][j] == 0)
{
que.push(make_pair(matrix[i + 1][j], (i + 1)*col + j));
visited[i + 1][j] = 1;
}
if (j + 1 < col&&visited[i][j + 1] == 0)
{
que.push(make_pair(matrix[i][j + 1], i*col + (j + 1)));
visited[i][j + 1] = 1;
}
}
}
};
#endif