题目
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路
这道题借鉴的是归并排序的思想。前面已经实现了两个链表的合并,把一个链表看成一个元素,模仿归并排序的过程,很容易实现。
代码
<pre name="code" class="java">/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null)
return null;
int len = lists.length;
if (len == 0)
return null;
if(len == 1)
return lists[0];
int mid = (len - 1)/2 ;
ListNode l1 = mergeKLists(Arrays.copyOfRange(lists, 0, mid + 1));
ListNode l2 = mergeKLists(Arrays.copyOfRange(lists, mid + 1, len));
return mergeTwoLists(l1, l2);
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null)
return l2;
if(l2 == null)
return l1;
ListNode head = new ListNode(0);
ListNode curr = head;
while(l1 != null && l2 != null) {
int num1 = l1.val;
int num2 = l2.val;
int num3 = 0;
if (num1 < num2) {
num3 = num1;
l1 = l1.next;
}
else {
num3 = num2;
l2 = l2.next;
}
curr.next = new ListNode(num3);
curr = curr.next;
}
if (l1 != null)
curr.next = l1;
else
curr.next = l2;
return head.next;
}
}