马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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.
1.PriorityQueue
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public int kthSmallest(int[][] matrix, int k) {
PriorityQueue <Integer> queue = new PriorityQueue <Integer>(matrix.length*matrix.length, new Comparator<Integer>(){
public int compare(Integer n1, Integer n2){
return n1 - n2;
}
});
for(int i = 0 ; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
queue.offer(matrix[i][j]);
}
}
int i = queue.peek();
while(k != 0){
i = queue.remove();
k--;
}
return i;
}
}
2.二分法
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int row = matrix.length, col = matrix[0].length;
int start = matrix[0][0], end = matrix[row-1][col-1];
while(start <= end){
int mid = (end - start)/2 + start;
if(count(matrix, mid) >= k) end = mid - 1;
else
start = mid + 1;
}
return start;
}
public int count(int[][] matrix, int n){
int row = matrix.length, col = matrix[0].length;
int c = col - 1;
int count = 0;
for(int i = 0; i < row ; i++){
while(c >= 0 && matrix[i][c] > n) c--;
count += c + 1;
}
return count;
}
}
|