diff --git a/src/p23_merge_k_sorted_lists.rs b/src/p23_merge_k_sorted_lists.rs index 9a82e0f..30d0728 100644 --- a/src/p23_merge_k_sorted_lists.rs +++ b/src/p23_merge_k_sorted_lists.rs @@ -1,27 +1,90 @@ -use super::linked_list::ListNode; +pub mod sorted_vec { + use crate::linked_list::ListNode; + + pub struct Solution; + impl Solution { + pub fn merge_k_lists(lists: Vec>>) -> Option> { + let mut nums = vec![]; + for mut list in lists { + while let Some(node) = list { + nums.push(node.val); + list = node.next; + } + } + nums.sort(); + let mut head = None; + let mut tail = &mut head; + for num in nums { + *tail = Some(Box::new(ListNode::new(num))); + tail = &mut tail.as_mut().unwrap().next; + } + return head; + } + } -pub struct Solution; -impl Solution { - // TODO: implement - pub fn merge_k_lists(lists: Vec>>) -> Option> { - - return None; + #[test] + fn test1() { + assert_eq!(Solution::merge_k_lists(vec![ + list![1,4,5], list![1,3,4], list![2,6] + ]), list![1,1,2,3,4,4,5,6]); + } + + #[test] + fn test2() { + assert_eq!(Solution::merge_k_lists(vec![]), list![]); + } + + #[test] + fn test3() { + assert_eq!(Solution::merge_k_lists(vec![list![]]), list![]); } } -#[test] -fn test1() { - assert_eq!(Solution::merge_k_lists(vec![ - list![1,4,5], list![1,3,4], list![2,6] - ]), list![1,1,2,3,4,4,5,6]); -} +pub mod binary_heap { + use crate::linked_list::ListNode; + use std::{collections::BinaryHeap, cmp::{Ordering, Reverse}}; -#[test] -fn test2() { - assert_eq!(Solution::merge_k_lists(vec![]), list![]); -} + pub struct Solution; + impl Solution { + pub fn merge_k_lists(lists: Vec>>) -> Option> { + let mut lists = lists.into_iter() + .filter(Option::is_some) + .map(Reverse) + .collect::>(); + let mut head = None; + let mut tail = &mut head; + while let Some(Reverse(mut list)) = lists.pop() { + let next = list.as_mut().unwrap().next.take(); + *tail = list; + tail = &mut tail.as_mut().unwrap().next; + if next.is_some() { lists.push(Reverse(next)); } + } + return head; + } + } -#[test] -fn test3() { - assert_eq!(Solution::merge_k_lists(vec![list![]]), list![]); + impl PartialOrd for ListNode { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } + } + + impl Ord for ListNode { + fn cmp(&self, other: &Self) -> Ordering { self.val.cmp(&other.val) } + } + + #[test] + fn test1() { + assert_eq!(Solution::merge_k_lists(vec![ + list![1,4,5], list![1,3,4], list![2,6] + ]), list![1,1,2,3,4,4,5,6]); + } + + #[test] + fn test2() { + assert_eq!(Solution::merge_k_lists(vec![]), list![]); + } + + #[test] + fn test3() { + assert_eq!(Solution::merge_k_lists(vec![list![]]), list![]); + } }