LeetCode每日一题(Kth Smallest Element in a Sorted Matrix)

该篇博客介绍了如何在给定的行和列都按升序排列的矩阵中,利用二叉堆寻找第k小的元素。通过创建一个堆并将矩阵的第一列元素插入堆中,然后在每次弹出堆顶元素后检查是否达到目标k,实现高效查找。提供的Rust代码展示了具体实现过程。
摘要由CSDN通过智能技术生成

Given an n x n matrix where each of the rows and columns are sorted in ascending order, return 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 1:

Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13

Example 2:

Input: matrix = [[-5]], k = 1
Output: -5

Constraints:

  • n == matrix.length
  • n == matrix[i].length
  • 1 <= n <= 300
  • -109 <= matrix[i][j] <= 109
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
  • 1 <= k <= n2

代码(Rust):

use std::cmp::{Ordering, Reverse};
use std::collections::BinaryHeap;

#[derive(Eq, PartialEq)]
struct Node(i32, usize, usize);

impl Ord for Node {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

impl PartialOrd for Node {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl Solution {
    pub fn kth_smallest(matrix: Vec<Vec<i32>>, k: i32) -> i32 {
        let mut heap: BinaryHeap<Reverse<Node>> = BinaryHeap::new();
        // 把每一行的第一个元素放到堆里
        for i in 0..matrix.len() {
            heap.push(Reverse(Node(matrix[i][0], i, 0)));
        }
        let mut count = 0;
        let mut result = 0;
        while !heap.is_empty() {
            // 弹出最小的元素
            let mut node = heap.pop().unwrap().0;
            result = node.0;
            count += 1;
            if count == k {
                break;
            }
            // 如果该行还有剩余元素, 将下一个元素推进堆
            if node.2 < matrix[0].len() - 1 {
                node.2 += 1;
                node.0 = matrix[node.1][node.2];
                heap.push(Reverse(node));
            }
        }
        result
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值