您的位置:首页 > 其它

leetcode(378):Kth Smallest Element in a Sorted Matrix

2017-01-07 19:49 369 查看
【题目】

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.

题意为求一个行和列按升序排列的整形数组的第k小的整数

用到PriorityQueue,设置特殊的数据结构,存储数和其对应的行和列,入队时按照value大小自动排序。

每出队一个元素,将这个元素的右边和下面的元素入队

【java】

public class Solution {
public int kthSmallest(int[][] matrix, int k) {
if(k==1||matrix.length==1||matrix[0].length==1) return matrix[0][0];
Comparator<Struct> compare = new Comparator<Struct>() {

@Override
public int compare(Struct o1, Struct o2) {
return o1.v-o2.v;
}
};
PriorityQueue<Struct> queue = new PriorityQueue<>(k,compare);
int rowSum = matrix.length,colSum = matrix[0].length;
boolean[][] bool = new boolean[rowSum][colSum];
queue.offer(new Struct(matrix[0][0],0,0));
bool[0][0] = true;
for (int i = 1; i <=k &&!queue.isEmpty(); i++) {
Struct st = queue.poll();
int x = st.row;
int y = st.col;
if(y+1<colSum&& !bool[x][y+1]){
queue.offer(new Struct(matrix[x][y+1],x,y+1));
bool[x][y+1]=true;
}
if(x+1<rowSum && !bool[x+1][y]){
queue.offer(new Struct(matrix[x+1][y],x+1,y));
bool[x+1][y]=true;
}
if(i==k) return st.v;
}
return 0;
}
class Struct{
int v;
int col;
int row;
public Struct(int v,int row,int col){
this.v = v;
this.row = row;
this.col=col;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: