赞
踩
example
input : matrix = [[1, 5, 9],[10, 11, 13],[12, 13, 15]], k = 8
output : 13
input : matrix = [[-5]], k = 1
output : -5
思路1 排序
思路2 二分查找
思路1代码
public class Solution1 {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int[] array = new int[n * n];
int t = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
array[t++] = matrix[i][j];
}
}
Arrays.sort(array);
return array[k - 1];
}
}
思路2代码
public class Solution2 { public int kthSmallest(int[][] matrix, int k) { int n = matrix.length; int left = matrix[0][0]; int right = matrix[n - 1][n - 1]; while (left < right) { int mid = left + ((right - left) >> 1); int count = findSmaller(matrix, mid, n); if (count < k) { left = mid + 1; } else { right = mid; } } return right; } private int findSmaller(int[][] matrix, int mid, int n) { int count = 0; int i = n - 1; int j = 0; while (i >= 0 && j < n) { if (matrix[i][j] <= mid) { count += i + 1; j++; } else { i--; } } return count; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。