LeetCode#378 有序矩阵中第k小的元素

本文介绍了一种使用小根堆寻找nxn升序矩阵中第k小元素的方法。通过实例演示了如何利用优先队列实现算法,并确保k的有效性在1到n²之间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
请注意,它是排序后的第 k 小元素,而不是第 k 个不同的元素。

示例:

matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

返回 13。

方法一:小根堆

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>(){
            public int compare(int[] o1,int[] o2){
                return o1[0] - o2[0];
            }
        });
        int n = matrix.length;
        for(int i=0;i<n;i++){
            queue.offer(new int[]{matrix[i][0],i,0});
        }
        for(int i=0;i<k-1;i++){
            int temp[] = queue.poll();
            if(temp[2] < n - 1){
                queue.offer(new int[]{matrix[temp[1]][temp[2]+1],temp[1],temp[2] + 1});
            }
        }
        return queue.poll()[0];
    }
}

提示:
你可以假设 k 的值永远是有效的,1 ≤ k ≤ n2 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值