378. 有序矩阵中第K小的元素
普通解法:
class Solution {
public int kthSmallest(int[][] matrix, int k) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
list.add(matrix[i][j]);
}
}
Collections.sort(list);
return list.get(k-1);
}
}
二分解法:
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n=matrix.length;
int l=matrix[0][0],r=matrix[n-1][n-1],mid;
while (l<r){
mid=(l+r)>>1;
if(Check(matrix,k,mid,n)){
r=mid;
}else{
l=mid+1;
}
}
return l;
}
static boolean Check(int[][] matrix,int k,int mid,int n){
int i=n-1;
int j=0;
int num=0;
while(i>=0&&j<n){
if(matrix[i][j]<=mid){
num+=i+1;
j++;
}else{
i--;
}
}
return num>=k;
}
}