【发布时间】:2021-09-07 12:34:29
【问题描述】:
我的问题受到this particular SO comment 的启发,没有答案(我自己也面临这个问题):
我是trying to findK排序矩阵中最小的元素:
给定一个 n x n 矩阵,其中每一行和每一列都按升序排序,返回矩阵中第 k 个最小的元素。
请注意,它是排序顺序中第 k 个最小的元素,而不是第 k 个不同的元素。
输入:矩阵 = [[1,5,9],[10,11,13],[12,13,15]], k = 8
输出:13
说明:矩阵中的元素为[1,5,9,10,11,12,13,13,15],第8小数为13。
我的代码是这样的:
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;
}
};
注释的代码返回矩阵中存在的数字 (13),而未注释的代码返回矩阵中不的14。
什么给了?找到矩阵中存在的数字背后的直觉是什么? ideone 上的工作代码here。
【问题讨论】:
-
很确定这只是巧合,一个返回数组中的元素,另一个没有。尝试使用矩阵的代码,其中数字都分开很远,例如
[1, 100, 1000], [10, 150, 1500], [30, 300, 3000]。这将减少lowest最终成为矩阵中的数字的可能性。 -
@user3386109,我用
k=8试过你的例子。我得到带有注释代码的1500,而我的(未注释的)代码返回2999。 -
k=7怎么样? -
@user3386109,对于
k=7,注释代码为1000,而未注释代码为1499。 -
@user3386109,我在ideone 上设置了一个工作示例。
标签: c++ algorithm matrix binary-search