From 7a5e2cc77cdaa1052c9044834fe0324cb1f33b58 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Mon, 22 Sep 2025 10:47:32 +0800 Subject: [PATCH] feat: 23_merge_k_sorted_lists --- 23_merge_k_sorted_lists/Cargo.lock | 7 ++++ 23_merge_k_sorted_lists/Cargo.toml | 6 +++ 23_merge_k_sorted_lists/src/lib.rs | 62 ++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 23_merge_k_sorted_lists/Cargo.lock create mode 100644 23_merge_k_sorted_lists/Cargo.toml create mode 100644 23_merge_k_sorted_lists/src/lib.rs diff --git a/23_merge_k_sorted_lists/Cargo.lock b/23_merge_k_sorted_lists/Cargo.lock new file mode 100644 index 0000000..82f4800 --- /dev/null +++ b/23_merge_k_sorted_lists/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "merge_k_sorted_lists" +version = "0.1.0" diff --git a/23_merge_k_sorted_lists/Cargo.toml b/23_merge_k_sorted_lists/Cargo.toml new file mode 100644 index 0000000..44b7d66 --- /dev/null +++ b/23_merge_k_sorted_lists/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "merge_k_sorted_lists" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/23_merge_k_sorted_lists/src/lib.rs b/23_merge_k_sorted_lists/src/lib.rs new file mode 100644 index 0000000..21833c1 --- /dev/null +++ b/23_merge_k_sorted_lists/src/lib.rs @@ -0,0 +1,62 @@ +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option>, +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { next: None, val } + } +} + +#[derive(Eq)] +struct List { + head: Box, +} + +impl PartialEq for List { + fn eq(&self, other: &Self) -> bool { + self.head.val == other.head.val + } +} + +impl Ord for List { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.head.val.cmp(&self.head.val) + } +} + +impl PartialOrd for List { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +pub struct Solution; + +impl Solution { + pub fn merge_k_lists(lists: Vec>>) -> Option> { + let mut result_head = None; + let mut result = &mut result_head; + + let mut heap = std::collections::BinaryHeap::::new(); + for l in lists { + if let Some(head) = l { + heap.push(List { head: head }); + } + } + + while let Some(top) = heap.pop() { + *result = Some(Box::new(ListNode::new(top.head.val))); + result = &mut result.as_mut().unwrap().next; + + if let Some(new_top_head) = top.head.next { + heap.push(List { head: new_top_head }); + } + } + + result_head + } +}