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

【题目】
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;
    }
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值