Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. impl Solution {
  2. pub fn merge2(
  3. lists: &mut Vec<Option<Box<ListNode>>>,
  4. s: usize,
  5. e: usize,
  6. ) -> Option<Box<ListNode>> {
  7. fn move_head(src: &mut Option<Box<ListNode>>, dst: &mut Option<Box<ListNode>>) {
  8. if let Some(mut node) = src.take() {
  9. *src = node.next.take();
  10. node.next = dst.take();
  11. *dst = Some(node);
  12. }
  13. }
  14.  
  15. if s == e {
  16. return lists[s].take();
  17. } else {
  18. let mid = (s + e) / 2;
  19. let mut lhs = Solution::merge2(lists, s, mid);
  20. let mut rhs = Solution::merge2(lists, mid + 1, e);
  21. let mut head = None;
  22. while lhs.is_some() && rhs.is_some() {
  23. let lhs_head = lhs.as_ref().unwrap();
  24. let rhs_head = rhs.as_ref().unwrap();
  25. if lhs_head.val <= rhs_head.val {
  26. move_head(&mut lhs, &mut head);
  27. } else {
  28. move_head(&mut rhs, &mut head);
  29. }
  30. }
  31. while lhs.is_some() {
  32. move_head(&mut lhs, &mut head);
  33. }
  34. while rhs.is_some() {
  35. move_head(&mut rhs, &mut head);
  36. }
  37. let mut ans = None;
  38. while head.is_some() {
  39. move_head(&mut head, &mut ans);
  40. }
  41. ans
  42. }
  43. }
  44.  
  45. pub fn merge_k_lists(mut lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
  46. if lists.is_empty() {
  47. None
  48. } else {
  49. let (s, e) = (0, lists.len() - 1);
  50. Solution::merge2(&mut lists, s, e)
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement