this is a google interview question :
Given a N*N Matrix. All rows are sorted, and all columns are sorted. Find the Kth Largest element of the matrix.
doing
The following is my C++ solution, which is based on a min heap. When a cell in the matrix is on the top of the min heap, the number at the right and/or the downside will be inserted into the heap.
#include
#include
#include
using namespace std;
struct Entry {
int value;
int x;
int y;
bool operator < (const Entry& other) {
return this->value > other.value;
}
};
bool getKthNumber(int* matrix, int row, int col, int k, int* result){
if(matrix == NULL || row <= 0 || col <= 0 || result == NULL)
return false;
if(k <= 0 || k > row * col)
return false;
vector minHeap;
Entry first = {matrix[0], 0, 0};
minHeap.push_back(first);
make_heap(minHeap.begin(), minHeap.end());
for(int i = 0; i < k; ++i){
first = minHeap[0];
int x = first.x;
int y = first.y;
if(first.y == 0 && first.x < row - 1){
Entry next = {matrix[(x + 1) * col], x + 1, y};
minHeap.push_back(next);
push_heap(minHeap.begin(), minHeap.end());
}
if(first.y < col - 1){
Entry next = {matrix[x * col + y + 1], x, y + 1};
minHeap.push_back(next);
push_heap(minHeap.begin(), minHeap.end());
}
pop_heap(minHeap.begin(), minHeap.end());
minHeap.pop_back();
}
*result = first.value;
return true;
}