leetcode刷题之 数组与矩阵(5):有序矩阵的 Kth Element

[LeetCode] Kth Smallest Element in a Sorted Matrix 有序矩阵中第K小的元素

 

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.

小顶堆实现:主要原理是弹出k - 1个比他小的 最后堆顶的就是第k小的               o1-o2 正负是对于o2而言的标准

大顶堆:最后留下k个元素,堆定就是需要的                                                        o2-o1

这里用的小顶堆,首先 把第一行的元素全部加进去,实现一个堆。第二步:由于是每行顺序排列,弹出的堆顶元素也会根据每行顺序依次弹出,故只需要t.x再加一就得到下一行的元素,比如可以t.1+1, t.2+1,执行k-1次就找到第k小的元素了。当然需要判断有没有到最后一行,到了就无需再加。

public int kthSmallest(int[][] matrix, int k) {
    int m = matrix.length, n = matrix[0].length;
    PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
    for(int j = 0; j < n; j++) pq.offer(new Tuple(0, j, matrix[0][j]));
    for(int i = 0; i < k - 1; i++) { // 小根堆,去掉 k - 1 个堆顶元素,此时堆顶元素就是第 k 的数
        Tuple t = pq.poll();
        if(t.x == m - 1) continue;
        pq.offer(new Tuple(t.x + 1, t.y, matrix[t.x + 1][t.y]));
    }
    return pq.poll().val;
}

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;
    }
}
class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        int m = matrix.length, n = matrix[0].length;
        PriorityQueue<Tuple> pq = new PriorityQueue<>();
        for(int i = 0; i < n; i++)
            pq.add(new Tuple(0, i, matrix[0][i]));
        for(int j = 0; j < k-1; j++){
            Tuple t = pq.poll();
            if(t.x == m - 1)
                continue;
            pq.add(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
        }
        return pq.poll().val;
    }
    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;
        }
        public int compareTo(Tuple that){
            return this.val - that.val;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值