難度: Middle
類型: Array,Binary Search,Sorting,Heap (Priority Queue),Matrix,
Given an n x n matrix where each of the rows and columns is 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.
You must find a solution with a memory complexity better than O(n2).
Example 1:
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
Example 2:
Input: matrix = [[-5]], k = 1 Output: -5
Constraints:
n == matrix.length == matrix[i].length1 <= n <= 300-109 <= matrix[i][j] <= 109- All the rows and columns of
matrixare guaranteed to be sorted in non-decreasing order. 1 <= k <= n2
Follow up:
- Could you solve the problem with a constant memory (i.e.,
O(1)memory complexity)? - Could you solve the problem in
O(n)time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.
Consideration:
1. No create new vector or multiset to save memory.
2. Binary search to save time/complexity. (mid value from left-smallest to right-largest)
3. left-upper corner is the smallest value, and right-bottom corner is the largest value.
4. When [left to middle] number counts are more than k, k smallest value is in the [left to middle] part. otherwise, it would be in the [middle+1 to right] part.
5. When matrix[i][j] < middle, it means all element at matrix(i, 0~j) will be less than middle. Then you may check next column matrix(i+1, 0~j).
Code:
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int n = matrix[0].size();
cout << "n = " << n << "\n";
int left = matrix[0][0];
int right = matrix[n-1][n-1];
int mid;
while (left<right)
{
mid = (left + right)>>1;
if (left_check(matrix, mid, k, n))
{
right = mid;
}
else
{
left = mid + 1;
}
}
return left;
}
private:
bool left_check(vector<vector<int>>& matrix, int mid, int k, int n)
{
int count=0;
int i=n-1;
int j=0;
while ((j<n) && (i>=0))
{
if (mid>=matrix[i][j])
{
count+=(i+1);
++j;
}
else
--i;
}
return count >= k;
}
};
Result:
Result:
Runtime
0msBeats100.00%
Memory
17.06MBBeats80.01%