题目
leetcode378-有序矩阵中第K小的元素
英文链接:
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
中文链接:
https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/
分类:二分查找类
题目详述
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 请注意,它是排序后的第k小元素,而不是第k个元素。
示例:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,返回 13。
说明: 你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。
暴力解决
思路
代码
class Solution {
public int kthSmallest(int[][] matrix, int k) {
if(matrix.length == 0 || matrix[0].length == 0)
return -1;
int rows = matrix.length;
int cols = matrix[0].length;
int number = rows * cols;
int [] list = new int[number];
int count = 0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
list[count] = matrix[i][j];
count++;
}
}
Arrays.sort(list);
return list[k-1];
}
}
二分解决
思路
代码
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int left = matrix[0][0], right = matrix[n - 1][n - 1];
while (left + 1 < right) {
int mid = (right - left) / 2 + left;
int num = count(matrix, mid);
if (num >= k) {
right = mid;
} else {
left = mid;
}
}
if (count(matrix, right) <= k - 1) return right;
return left;
}
public int count(int[][] matrix, int target) {
int n = matrix.length;
int i = n - 1, j = 0;
int res = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] < target) {
res += i + 1; //index + 1 = number of elements.
j++;
} else {
i--;
}
}
return res;
}
}
代码讲解
结束语
2018.11.1打卡~
END