Implemented p23 with 2 different solutions

This commit is contained in:
Egor 2024-05-04 02:21:38 +03:00
parent e57953fd8c
commit b7efae53d1

View file

@ -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<Box<ListNode>>>) -> Option<Box<ListNode>> {
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<Box<ListNode>>>) -> Option<Box<ListNode>> {
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<Box<ListNode>>>) -> Option<Box<ListNode>> {
let mut lists = lists.into_iter()
.filter(Option::is_some)
.map(Reverse)
.collect::<BinaryHeap<_>>();
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<Ordering> { 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![]);
}
}