Monday, August 8, 2016

378. Kth Smallest Element in a Sorted Matrix

I tried a way of moving two pointers from top left/bottom right corner but found it is not able to solve the problem. Then I followed the top rated solution to solve the problem by minimal heap.
The idea is to push the numbers of first row into the heap. The heap is ordered by the value of numbers. Once we pop out the top number, we need to find the next possible number. It will be  the number on next row in the same column with the popped number. Therefore, we need to append the position information to the number. So the code is as following:

1:  class Solution {  
2:  public:  
3:    int kthSmallest(vector<vector<int>>& matrix, int k) {  
4:      priority_queue<pair<int,pair<int, int>>, vector<pair<int,pair<int, int>>>, greater<pair<int, pair<int, int>>>> minHeap;  
5:      int n = matrix.size();  
6:      for (int j = 0; j < n; j++) {  
7:        minHeap.push(make_pair(matrix[0][j], make_pair(0, j)));  
8:      }  
9:      int res = 0;  
10:      while (k) {  
11:        int i = minHeap.top().second.first;  
12:        int j = minHeap.top().second.second;  
13:        res = matrix[i++][j];  
14:        minHeap.pop();  
15:        if (i < n ) minHeap.push(make_pair(matrix[i][j], make_pair(i, j)));  
16:        k--;  
17:      }  
18:      return res;  
19:    }  
20:  };  

No comments:

Post a Comment