Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
大概意思:将数组中的链表进行排序
public static void sort(ListNode[] lists, int low, int high) {
int start = low;
int end = high;
ListNode key = lists[low];
while (end > start) {
while (end > start && lists[end].val >= key.val)
end--;
if (lists[end].val <= key.val) {
ListNode temp = lists[end];
lists[end] = lists[start];
lists[start] = temp;
}
while (end > start && lists[start].val <= key.val)
start++;
if (lists[start].val >= key.val) {
ListNode temp = lists[start];
lists[start] = lists[end];
lists[end] = temp;
}
}
if (start > low)
sort(lists, low, start - 1);
if (end < high)
sort(lists, end + 1, high);
}
public static ListNode mergeKLists(ListNode[] lists) {
List<ListNode> Alist = new ArrayList<ListNode>();
for(ListNode ln : lists) {
if(ln != null) {
Alist.add(ln);
}
}
if(Alist.size() == 0)
return null;
lists = Alist.toArray(new ListNode[Alist.size()]);
sort(lists, 0, lists.length - 1);
ListNode node = new ListNode(lists[0].val);
ListNode head = node;
for (int t = 0;;) {
if (t == lists.length - 1) {
node.next = lists[t].next;
return head;
} else if (lists[t].next == null) {
t++;
node.next = new ListNode(lists[t].val);
node = node.next;
continue;
}
for (int i = t + 1;; i++) {
ListNode temp = lists[t].next;
if (lists[i].val >= temp.val) {
int j = t;
while (j < i - 1) {
lists[j] = lists[++j];
}
lists[j] = temp;
break;
} else if(i == lists.length - 1) {
int j = t;
while (j < i) {
lists[j] = lists[++j];
}
lists[j] = temp;
break;
}
}
node.next = new ListNode(lists[t].val);
node = node.next;
}
}
看了一下别人的实现,没有我觉得特别好的,自己大概的思路是1.排序成一个数组 2.取出一个,利用插入排序将取出的那个链表下一次进行排序