题解 | 合并k个已排序的链表
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 输入:[{1,2},{1,4,5},{6}] * 返回值: {1,1,2,4,5,6} * * @param lists ListNode类一维数组 * @return ListNode类 */ function mergeKLists(lists) { // write code here let head = new ListNode(); let res = head; // 至少需要两个才能进行大小比较 while (lists.filter((e) => e).length >= 2) { // 比较 lists 中多值的大小 let min = null; let minIndex = 0; lists.forEach((e, i) => { if (e) { if (min) { if (min.val > e.val) { min = e; minIndex = i; } } else { min = e; minIndex = i; } } }); res.next = min; lists[minIndex] = min.next; res = res.next; } const last = lists.filter((e) => e); res.next = last[0]; return head.next; } module.exports = { mergeKLists: mergeKLists, };