# Kth Smallest Element in a Sorted Matrix

608人阅读 评论(0)

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.


public int kthSmallest(int[][] matrix, int k) {
int i = 0;
int[] list = new int[(matrix.length) * (matrix.length)];
while(i< matrix.length){
int j = 0;
while(j< matrix.length){

list[((i) * matrix.length)+j] = matrix[i][j];
j++;
}
i++;
}
Arrays.sort(list);

return list[k-1];
}

public int kthSmallest(int[][] matrix, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer a0, Integer a1) {
if(a0>a1){
return -1;
}else if(a0<a1){
return 1;
}
return 0;
}
});// 最大堆
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (i * matrix.length + j + 1 > k) {
if (matrix[i][j] < heap.peek()) {
heap.poll();
heap.offer(matrix[i][j]);
}
} else {
heap.offer(matrix[i][j]);
}
}

}
return heap.peek();
}

class Tuple implements Comparable<Tuple> {
int x, y, val;
public Tuple (int x, int y, int val) {
this.x = x;
this.y = y;
this.val = val;
}

@Override
public int compareTo (Tuple that) {
return this.val - that.val;
}
}

public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
for(int j = 0; j <= n-1; j++){
System.out.println(matrix[0][j]);
pq.offer(new Tuple(0, j, matrix[0][j]));
}
for(int i = 0; i < k-1; i++) {
Tuple t = pq.poll();
System.out.println(t.val+"------");
if(t.x == n-1) {
continue;
}
System.out.println(matrix[t.x+1][t.y]+"****");
pq.offer(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
}
return pq.poll().val;
}

public int kthSmallest(int[][] matrix, int k)  {
int matrixRowSize=matrix.length;
int matrixColSize=matrix[0].length;
int minVal = matrix[0][0];
int maxVal = matrix[matrixRowSize-1][matrixColSize-1];
int midVal = 0;
int count = 0;
while (minVal < maxVal) {
midVal = (minVal + maxVal) / 2;
for (int i  = 0; i < matrixRowSize && matrix[i][0] <= midVal; i++) {
for (int j = 0; j < matrixColSize; j++) {
if (matrix[i][j] <= midVal) {
count++;
}
}
}
if (k <= count) {
maxVal = midVal;
} else {
minVal = midVal + 1;
}
count = 0;
}
return minVal;
}

个人资料
等级：
访问量： 6万+
积分： 2797
排名： 1万+
最新评论