My question is inspired by this particular SO comment which is unanswered (I am facing that problem myself):
I am trying to find the K
th smallest element in a sorted matrix:
Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13.
The code I have is this:
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int lowest=INT_MAX, highest=INT_MIN;
for(vector<int> row: matrix) {
lowest=min(lowest, row[0]);
highest=max(highest, row[row.size()-1]);
}
while(lowest<highest) {
int mid=lowest+(highest-lowest+1)/2;
int places=0;
for(int i=0; i<matrix.size(); i++) {
places+=(upper_bound(matrix[i].begin(), matrix[i].end(), mid)-matrix[i].begin());
}
if(places<=k) lowest=mid; //this gives a number _not_ in the matrix (14)
else highest=mid-1;
// if(places<k) lowest=mid+1; //this gives a number _in_ the matrix (13)
// else highest=mid; //also use mid=lowest+(highest-lowest)/2 instead;
}
return lowest;
}
};
The commented code returns a number that is present in the matrix (13
), whereas the uncommented code returns 14
, which is not in the matrix.
What gives? What is the intuition behind finding the number present in the matrix? Working code on ideone here.