问题描述
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
问题分析
我们可以使用以前写过的合并两条有序链表mergeTwoLists()函数,循环k次即可,复杂度是O(n*k)=O(n^2)。
代码实现
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if (lists.size() == 0) return null;
ListNode head = lists.get(0);
for (int i = 1; i < lists.size(); i++) {
head = mergeTwoLists(head, lists.get(i));
}
return head;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode cur = head;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1 == null) {
cur.next = l2;
}
if (l2 == null) {
cur.next = l1;
}
return head.next;
}
网友评论