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.lengthn == matrix[i].length1 <= n <= 300-109 <= matrix[i][j] <= 109- All the rows and columns of
matrixare 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
}
}
该篇博客介绍了如何在给定的行和列都按升序排列的矩阵中,利用二叉堆寻找第k小的元素。通过创建一个堆并将矩阵的第一列元素插入堆中,然后在每次弹出堆顶元素后检查是否达到目标k,实现高效查找。提供的Rust代码展示了具体实现过程。

被折叠的 条评论
为什么被折叠?



