合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
思路:分治思想。处理相加为len-1的数据。也就是0对应的len-i-1。类似归并排序思想。两两对应处理。
private static class ListNode {
private int val
private ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if (len == 0) {
return null;
}
//使用分治法思想,两两合并。归并排序类似
while (len > 1) {
//分治处理,
for (int i = 0; i < len / 2; i++) {
lists[i] =mergeTowList(lists[i], lists[len - 1 - i]);
}
//处理后剩余数量
len = (len + 1)/2;
}
return lists[0];
}
public static ListNode mergeTowList(ListNode first, ListNode second) {
//设置一个哨兵服务结点
ListNode head = new ListNode(-1);
ListNode p = head;
while (first != null && second != null) {
if (first.val < second.val) {
p.next = first;
first = first.next;
} else {
p.next = second;
second = second.next;
}
p = p.next;
}
if (first != null) {
p.next = first;
}
if (second != null) {
p.next = second;
}
//取下一个结点
return head.next;
}
网友评论