Selection algorithms on sorted matrix

后端 未结 8 1780
野性不改
野性不改 2020-11-28 22:51

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

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 23:15

    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;
    }
    

提交回复
热议问题