-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeKSortedLists.java
49 lines (48 loc) · 1.44 KB
/
mergeKSortedLists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
import java.util.*;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0 || lists == null) {
return null;
}
return mergeKListsHelper(lists, 0, lists.length - 1);
}
static ListNode mergeKListsHelper(ListNode[] lists, int start, int end){
if(start == end){
return lists[start];
}
if(start + 1 == end){
return mergeLL(lists[start], lists[end]);
}
int mid = start + (end - start) / 2;
ListNode left = mergeKListsHelper(lists, start, mid);
ListNode right = mergeKListsHelper(lists, mid + 1, end);
return mergeLL(left, right);
}
static ListNode mergeLL(ListNode head1, ListNode head2){
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while(head1 != null && head2 != null){
if(head1.val < head2.val){
curr.next = head1;
head1 = head1.next;
}
else{
curr.next = head2;
head2 = head2.next;
}
curr = curr.next;
}
curr.next = (head1 != null) ? head1 : head2;
return dummy.next;
}
}