解法1:最笨的解法
public class _23_合并K个排序链表 {
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;
}
}
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 class _23_合并K个排序链表 {
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;
}
}
if (minIndex == -1) break;
cur = cur.next = lists[minIndex];
lists[minIndex] = lists[minIndex].next;
}
return head.next;
}
}
解法3:逐一两两合并
public class _23_合并K个排序链表 {
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;
}
}
解法4:优先级队列(小顶堆)
public class _23_合并K个排序链表 {
public ListNode mergeKLists4(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
ListNode head = new ListNode(0);
ListNode cur = head;
PriorityQueue<ListNode> queue = new PriorityQueue<>((ListNode node1, ListNode node2) -> {
return node1.val - node2.val;
});
for (ListNode list : lists) {
if (list == null) continue;
queue.offer(list);
}
while (!queue.isEmpty()) {
ListNode node = queue.poll();
cur = cur.next = node;
if (node.next != null) {
queue.offer(node.next);
}
}
return head.next;
}
}
解法5:分治策略
public class _23_合并K个排序链表 {
public ListNode mergeKLists5(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
int step = 1;
while (step < lists.length) {
int nextStep = step << 1;
for (int i = 0; i + step < lists.length; i += nextStep) {
lists[i] = mergeTwoLists(lists[i], lists[i + step]);
}
step = nextStep;
}
return lists[0];
}
}