378. Kth Smallest Element in a Sorted Matrix | LeetCode Solution
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
matrix are 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.
class Solution {public: int kthSmallest(vector<vector<int>>& v, int k) { int st=v[0][0]; int m=v.size(); int n=v[0].size(); int end=v[m-1][n-1]; int mid; while(st<=end){ mid=(end+st)/2; int ans=0; for(int i=0; i<m; i++){ int low=0,high=n-1,mi; while(low<=high){ mi=low+(high-low)/2; if(v[i][mi]<=mid)low=mi+1; else high=mi-1; } ans+=low; } if(ans<k)st=mid+1; else end=mid-1; } return st; }};
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.
class Solution {
public:
int kthSmallest(vector<vector<int>>& v, int k) {
int st=v[0][0];
int m=v.size();
int n=v[0].size();
int end=v[m-1][n-1];
int mid;
while(st<=end){
mid=(end+st)/2;
int ans=0;
for(int i=0; i<m; i++){
int low=0,high=n-1,mi;
while(low<=high){
mi=low+(high-low)/2;
if(v[i][mi]<=mid)low=mi+1;
else high=mi-1;
}
ans+=low;
}
if(ans<k)st=mid+1;
else end=mid-1;
}
return st;
}
};
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.