学习地址B站https://www.bilibili.com/video/BV1mK411N7pu?from=search&seid=3121723007892517064
public class _003_23_合并K个链表 {
//思路1 最笨的方法
public ListNode mergeKLists1(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
//将所有节点添加到数组中
List<ListNode> nodes = new ArrayList<>();
for (ListNode list : lists) {
while (list != null) {
nodes.add(list);
list = list.next;
}
}
//对数组进行排序 (基于比较的排序,时间复杂度目前最好是O(nlogn),n是所有节点的数量)
nodes.sort((ListNode node1, ListNode node2) -> {
return node1.val - node2.val;
});
//将排好序的节点串起来
ListNode head = new ListNode(0);
ListNode cur = head;
for (ListNode node : nodes) {
cur = cur.next = node;
}
return head.next;
}
}
//思路2 逐一比较
public ListNode mergeKLists2(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
ListNode head = new ListNode(0);
ListNode cur = head;
while (true) {
//最小链表节点所在的索引
int minIndex = -1;
for (int i = 0; i < lists.length; i++) {
if (lists[i] == null) continue;
if (minIndex == -1 || lists[i].val < lists[minIndex].val) {
minIndex = i;
}
} //O(k)
// 所有链表节点已经串起来了
if (minIndex == -1) break;
cur = cur.next = lists[minIndex];
lists[minIndex] = lists[minIndex].next;
}// O(kn)
return head.next;
}
//思路3 逐一两两合并
public ListNode mergeKLists3(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
for (int i = 1; i < lists.length; i++){
lists[0] = mergeTwoLists(lists[0], lists[i]);
}
return lists[0];
}
//虚拟头结点
private ListNode head = new ListNode(0);
public ListNode mergeTwoLists(ListNode k1, ListNode k2) {
if (k1 == null) return k2;
if (k2 == null) return k1;
head.next =null;
ListNode cur = head;
while (k1 != null && k2 != null) {
if (k1.val <= k2.val) {
cur = cur.next = k1;
k1 = k1.next;
}else {
cur = cur.next = k2;
k2 = k2.next;
}
}
if (k1 == null){
cur.next = k2;
}else if (k2 == null){
cur.next = k1;
}
return head.next;
}