23. 合并K个排序链表
题目描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
实现1
每次取出两个链表,合并成一个
/**
* 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;
}
ListNode res = lists[0];
for (int i = 1; i < lists.length; i++) {
res = insert(res, lists[i]);
}
return res;
}
public ListNode insert(ListNode list, ListNode list2) {
if(list == null) {
return list2;
}
if(list2 == null) return list;
if(list.val > list2.val) {
ListNode temp = list;
list = list2;
list2 = temp;
}
ListNode pre = list;
ListNode next = list.next;
while(list2 != null && pre != null) {
if(pre.val <= list2.val && next == null) {
pre.next = list2;
break;
} else if(pre.val <= list2.val && next.val > list2.val) {
pre.next = list2;
list2 = list2.next;
pre = pre.next;
pre.next = next;
} else {
pre = next;
next = next.next;
}
}
return list;
}
}
实现2
分治
/**
* 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 merger(lists, 0, lists.length - 1);
}
public ListNode merger(ListNode[] lists, int left, int right) {
if(left == right) {
return lists[left];
}
int mid = left + (right - left) / 2;
ListNode list1 = merger(lists, left, mid);
ListNode list2 = merger(lists, mid + 1, right);
return mergerTwoLists(list1, list2);
}
public ListNode mergerTwoLists(ListNode list1, ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
if(list1.val > list2.val) {
ListNode temp = list1;
list1 = list2;
list2 = temp;
}
ListNode pre = list1;
ListNode next = list1.next;
while(list2 != null) {
if(pre.val <= list2.val && next == null) {
pre.next = list2;
break;
} else if(pre.val <= list2.val && next.val > list2.val) {
ListNode temp = list2;
list2 = list2.next;
temp.next = next;
pre.next = temp;
pre = temp;
} else {
pre = next;
next = next.next;
}
}
return list1;
}
}
来源:CSDN
作者:csdnyq
链接:https://blog.csdn.net/csdnyq/article/details/103757201