Original address: https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/submissions/
Title Description:
Given an n x n matrix, the elements of each row and column are sorted in ascending order, and the k-th smallest element in the matrix is found.
Note that it is the k-th small element after sorting, not the k-th element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
Return to 13.
Explanation:
You can assume that the value of k is always valid, 1 ≤ k ≤ n2.
Solution:
General convenience search, each cycle, to find the current minimum value. The idea is relatively direct, the time complexity is not low, and binary search is not used.
Code:
class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { int rowSize = matrix.size(); if (rowSize == 0){ return 0; } int colSize = matrix[0].size(); if (colSize == 0){ return 0; } int result;//Storage results vector<int> rowPtr(rowSize, 0);//Row pointer of row I represented by rowPtr[i]n, pointing to column subscript of row I while (k > 0){ int tempRes = INT_MAX, minIndex;//Used to record the current smallest element //Scan all line pointers, determine the current minimum value, and mark other lines for (int row = 0; row < rowSize; ++row){ //Rowptr [row] < colsize cannot be out of the range if (rowPtr[row] < colSize && matrix[row][rowPtr[row]] < tempRes){ tempRes = matrix[row][rowPtr[row]];//Update current minimum minIndex = row;//Mark the line of the minimum value } } result = tempRes;//Update results rowPtr[minIndex] += 1;//The row pointer of the currently found minimum value moves backward k -= 1; } return result; } };
The best solution uses binary search:
static int x = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }(); class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { int n=matrix.size(); int begin=matrix[0][0],end=matrix[n-1][n-1]; while(begin<end) { int mid=begin+(end-begin)/2; int pos=0; for(int i=0;i<n;i++) { pos+=upper_bound(matrix[i].begin(),matrix[i].end(),mid)-matrix[i].begin(); } if(pos<k) begin=mid+1; else end=mid; } return end; } };