题目描述
合并K个排序链表
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
解答思路
由于题目中给了我们k个链表,所以可以使用分治的思想来进行解决。具体就是将k个链表的范围不断进行二分,在递归的base条件中再将两条链表合并为一条有序的链表,跟归并排序的思想类似。
具体思路如下
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
return mergeSort(lists, 0, lists.length - 1);
}
public ListNode mergeSort(ListNode[] lists, int left, int right) {
if (left >= right) {
return lists[left];
}
int mid = left + ((right - left) >> 1);
ListNode l1 = mergeSort(lists, left, mid);
ListNode l2 = mergeSort(lists, mid + 1, right);
return merge(l1, l2);
}
public ListNode merge(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
cur = cur.next;
l1 = l1.next;
} else {
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if (l1 != null) {
cur.next = l1;
}
if (l2 != null) {
cur.next = l2;
}
return dummyHead.next;
}
}