Topic:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity
Idea 1:
Merge the first two, then merge the completed linked list and the rest of the list to merge the order
Time Complexity of O (m*n)
Code:
public static ListNode MergeKLists1 (listnode[] lists) {
int len = lists.length;
if (len = = 0) {
return null;
}else{
if (len = = 1) {
return lists[0];
}else{
ListNode Headl = new ListNode (-1);
ListNode head1 = lists[0], head2 = lists[1];
for (int i=0; i < len-1; i++) {
if (head1 = = null) {
Headl.next = head2;
}else{
if (head2 = = null) {
Headl.next = Head1;
}else{
Measuring the head1 length of a chain table
int len1 = 0;
ListNode ptr = head1;
while (ptr! = null) {
len1++;
ptr = Ptr.next;
}
Measuring the length of the head2
int len2 = 0;
ptr = head2;
while (ptr! = null) {
len2++;
ptr = Ptr.next;
}
ptr = Headl;
ListNode ptr1 = head1, ptr2 = head2;
for (int j=0; j< len1+len2; j + +) {
if (ptr1!=null && ptr2! = null) {
if (ptr1.val <= ptr2.val) {
Ptr.next = PTR1;
PTR1 = Ptr1.next;
ptr = Ptr.next;
}else{
Ptr.next = PTR2;
PTR2 = Ptr2.next;
ptr = Ptr.next;
}
}else{
if (PTR1 = = null) {
Ptr.next = PTR2;
PTR2 = Ptr2.next;
ptr = Ptr.next;
}else{
Ptr.next = PTR1;
PTR1 = Ptr1.next;
ptr = Ptr.next;
}
}
}
Head1 = Headl.next;
if (i+2 <= len-1) {
Head2 = lists[i+2];
}else{
Break
}
}//else (head1!=null && head2! = null)
}
}//for (int i=0; i < len-1; i++)
return headl.next;
}
}
}
Idea 2:
Divide and conquer the law
22 Merge, recursive call can be.
Since each linked list is already sorted, the list of linked lists can be treated as an array of sorted arrays, with a merge sort.
Time Complexity of O (n)
AC Through
Code:
public static ListNode mergeklists (listnode[] lists) {
Return mergeklists (lists, 0, lists.length-1);
}
The Divide and conquer method is effective
public static ListNode mergeklists (listnode[] lists, int start, int end) {
if (start = = end) {
return Lists[start];
}
if (Start > End) {
return null;
}
int mid = (start + end)/2;
ListNode head1 = mergeklists (lists, start, mid);
ListNode head2 = mergeklists (lists, mid+1, end);
ListNode Headl = new ListNode (-1);
ListNode ptr = Headl;
while (Head1 = null && head2! = null) {
if (head1.val <= head2.val) {
Ptr.next = Head1;
Head1 = Head1.next;
ptr = Ptr.next;
}else{
Ptr.next = head2;
Head2 = Head2.next;
ptr = Ptr.next;
}
}
while (head1! = null) {
Ptr.next = Head1;
Head1 = Head1.next;
ptr = Ptr.next;
}
while (head2! = null) {
Ptr.next = head2;
Head2 = Head2.next;
ptr = Ptr.next;
}
return headl.next;
}
Leetcode23 multiple sequenced lists for merging (Java version)