Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Last active January 26, 2017 07:36
Show Gist options
  • Save Chen-tao/a959a5643d355b1d8fa7b237791bafaf to your computer and use it in GitHub Desktop.
Save Chen-tao/a959a5643d355b1d8fa7b237791bafaf to your computer and use it in GitHub Desktop.
//https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
//---------------------------------------------------------------
// one v
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
long left = matrix[0][0], right = matrix[n - 1][n - 1];
while(left <= right){
long mid = left + (right - left) / 2;
int cnt = 0;
int i = n - 1;
int j = 0;//左下角开始
while (i >= 0 && j < n) {
int ld = matrix[i][j];
if (ld <= mid) {//小于mid代表当前列都小,则右移一列
++j;
cnt += i + 1;
} else {//大于mid上移一列继续比较
--i;
}
}
if (cnt < k) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return (int) left;
}
}
//-------------------------------------------------------------
// two method v
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int lo = matrix[0][0], hi = matrix[n - 1][n - 1];
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int count = getLessEqual(matrix, mid);
if (count < k) lo = mid + 1;
else hi = mid - 1;
}
return lo;
}
private int getLessEqual(int[][] matrix, int val) {
int res = 0;
int n = matrix.length, i = n - 1, j = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] > val) i--;
else {
res += i + 1;
j++;
}
}
return res;
}
}
@Chen-tao
Copy link
Author

Chen-tao commented Jan 26, 2017

Notice

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.

用二分查找法来做,我们由于是有序矩阵,那么左上角的数字一定是最小的,而右下角的数字一定是最大的,所以这个是我们搜索的范围,然后我们算出中间数字mid,由于矩阵中不同行之间的元素并不是严格有序的,所以我们要在每一行都查找一下mid,我们使用upper_bound,这个函数是查找第一个大于目标数的元素,如果目标数在比该行的尾元素大,则upper_bound返回该行元素的个数,如果目标数比该行首元素小,则upper_bound返回0, 我们遍历完所有的行可以找出中间数是第几小的数,然后k比较,进行二分查找,本解法的整体时间复杂度为O(nlgn*lgX),其中X为最大值和最小值的差值.

上面的解法还可以进一步优化到O(nlgX),其中X为最大值和最小值的差值,我们并不用对每一行都做二分搜索法,我们注意到每列也是有序的,我们可以利用这个性质,从数组的左下角开始查找,如果比目标值小,我们就向右移一位,而且我们知道当前列的当前位置的上面所有的数字都小于目标值,那么cnt += i+1,反之则向上移一位,这样我们也能算出cnt的值。其余部分跟上面的方法相同

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment