Advertisement
exmkg

Untitled

Dec 16th, 2024
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     int val;
  5.  *     ListNode next;
  6.  *     ListNode() {}
  7.  *     ListNode(int val) { this.val = val; }
  8.  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9.  * }
  10.  */
  11. class Solution {
  12.     public ListNode mergeKLists(ListNode[] lists) {
  13.         return mergeAllLists(lists, 0, lists.length - 1);
  14.     }
  15.  
  16.     private ListNode mergeAllLists(ListNode[] lists, int left, int right) {
  17.         if (left > right) return null;
  18.         if (left == right) return lists[left];
  19.  
  20.         int middle = (left + right) / 2;
  21.  
  22.         ListNode merged_left_half_lists = mergeAllLists(lists, left, middle);
  23.         ListNode merged_right_half_lists = mergeAllLists(lists, middle + 1, right);
  24.  
  25.         return mergeTwoSortedLists(merged_left_half_lists,
  26.                                    merged_right_half_lists);
  27.     }
  28.  
  29.     private ListNode mergeTwoSortedLists(ListNode l1, ListNode l2) {
  30.         if (l1 == null) return l2;
  31.         if (l2 == null) return l1;
  32.  
  33.         if (l1.val < l2.val) {
  34.             l1.next = mergeTwoSortedLists(l1.next, l2);
  35.             return l1;
  36.         } else {
  37.             l2.next = mergeTwoSortedLists(l1, l2.next);
  38.             return l2;
  39.         }
  40.  
  41.         // l1 -> merge(l1.next, l2)
  42.         // l2 -> merge(l2.next, l1)
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement