Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit be4a779

Browse files
committed
src/bin/merge-k-sorted-lists.rs
1 parent cc16750 commit be4a779

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

src/bin/merge-k-sorted-lists.rs

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
fn main() {}
2+
3+
struct Solution;
4+
5+
// Definition for singly-linked list.
6+
#[derive(PartialEq, Eq, Clone, Debug)]
7+
pub struct ListNode {
8+
pub val: i32,
9+
pub next: Option<Box<ListNode>>,
10+
}
11+
12+
impl ListNode {
13+
#[inline]
14+
fn new(val: i32) -> Self {
15+
ListNode {
16+
next: None,
17+
val,
18+
}
19+
}
20+
}
21+
22+
impl Solution {
23+
pub fn merge_k_lists1(lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
24+
let mut lists = lists;
25+
let (mut index, mut min_value) = (0usize, None);
26+
for (i, v) in lists.iter().enumerate() {
27+
match v {
28+
Some(x) => {
29+
if min_value.is_none() {
30+
min_value = Some(x.val);
31+
index = i;
32+
} else {
33+
if min_value.as_ref().unwrap().gt(&x.val) {
34+
min_value = Some(x.val);
35+
index = i;
36+
}
37+
}
38+
}
39+
None => ()
40+
}
41+
}
42+
43+
if index == 0 && min_value.is_none() {
44+
return None;
45+
}
46+
let mut root = lists[index].take();
47+
lists[index] = root.as_mut().unwrap().next.take();
48+
49+
root.as_mut().unwrap().next = Self::merge_k_lists(lists);
50+
51+
root
52+
}
53+
54+
pub fn merge_k_lists(lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
55+
let mut lists = lists;
56+
57+
if lists.is_empty() {
58+
return None;
59+
} else if lists.len() == 1 {
60+
return lists[0].take();
61+
}
62+
63+
let mut start = lists[0].take();
64+
let mut i = 1usize;
65+
while i < lists.len() {
66+
start = Self::f(vec![start, lists[i].take()]);
67+
i += 1;
68+
}
69+
70+
start
71+
}
72+
73+
fn f(mut lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
74+
match (lists[0].take(), lists[1].take()) {
75+
(Some(mut x), Some(mut y)) => {
76+
if x.val < y.val {
77+
x.next = Self::f(vec![x.next.take(), Some(y)]);
78+
Some(x)
79+
} else {
80+
y.next = Self::f(vec![Some(x), y.next.take()]);
81+
Some(y)
82+
}
83+
}
84+
(Some(x), None) => Some(x),
85+
(None, Some(y)) => Some(y),
86+
(None, None) => None
87+
}
88+
}
89+
}

0 commit comments

Comments
 (0)