题目
解题思路
- 暴力解法
遍历链表数组,合并每一条链表
- 两两合并法
遍历数组链表元素,合并其中的两个,不再是单独合并一个
注意:如果需要原有的数组,那么需要注意数组长度的使用应该是新长度;如果是构建新数组使用则无此问题
代码
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
/**
* 通过优先级队列实现,或者是通过合并两个链表实现
* 一个一个链表的合并可以实现功能的需求,而合并两个则是可以降低时间复杂度
* 将多个链表的合并问题分解到两个链表的合并,每一个新合成的链表与下一个链表进行合并
*/
function mergeKLists1(lists: Array<ListNode | null>): ListNode | null {
let res = null
for (const head of lists) {
res = merge2Lists(res, head)
}
return res
};
function merge2Lists(l1: ListNode | null, l2: ListNode | null): ListNode | null {
if (l1 === null) return l2;
if (l2 === null) return l1;
if (l1.val <= l2.val) {
l1.next = merge2Lists(l1.next, l2);
return l1;
} else {
l2.next = merge2Lists(l1, l2.next);
return l2;
}
}
// 通过两两合并降低时间复杂度,定义规则
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
let len: number = lists.length;
if (len === 0) return null
while (len > 1) {
let idx = 0; // 保持原有数组的复用
for (let i = 0; i < len; i += 2) {
if (i === len - 1) lists[idx++] = lists[i]; // 注意使用新长度
else lists[idx++] = merge2Lists(lists[i], lists[i + 1])
}
len = idx // 新长度的赋值
}
return lists[0];
}