【算法】【线性表】【链表】合并 K 个升序链表
1 题目
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]] 输出:[1,1,2,3,4,4,5,6] 解释:链表数组如下: [ 1->4->5, 1->3->4, 2->6 ] 将它们合并到一个有序链表中得到。 1->1->2->3->4->4->5->6
示例 2:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
提示:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i]
按 升序 排列lists[i].length
的总和不超过10^4
2 解答
底子是基于归并排序的思想,先拆再合,最后的落点其实就是两个有序链表的合并,跟两个有序数组的合并思想差不多哈:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length <= 0) { return null; } return mergeKListsWithSpilt(lists, 0, lists.length - 1); } private ListNode mergeKListsWithSpilt(ListNode[] lists, int start, int end) { if (start >= end) { return lists[start]; } // 先拆分 int middle = start + (end - start) / 2; ListNode leftNode = mergeKListsWithSpilt(lists, start, middle); ListNode rightNode = mergeKListsWithSpilt(lists, middle + 1, end); // 合并两个链表 if (leftNode == null) { return rightNode; } if (rightNode == null) { return leftNode; } // 头节点 ListNode head = new ListNode(); ListNode res = head; while (leftNode != null && rightNode != null) { if (leftNode.val < rightNode.val) { head.next = leftNode; leftNode = leftNode.next; } else { head.next = rightNode; rightNode = rightNode.next; } head = head.next; } while (leftNode != null) { head.next = leftNode; head = head.next; leftNode = leftNode.next; } while (rightNode != null) { head.next = rightNode; head = head.next; rightNode = rightNode.next; } return res.next; } }
加油。