题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类一维数组 * @return ListNode类 */ function mergeTwoLists(l1, l2) { if (!l1) return l2; if (!l2) return l1; if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l2.next, l1); return l2; } } function merge(lists) { let middle = Math.floor(lists.length / 2); let left = mergeKLists(lists.slice(0, middle)); let right = mergeKLists(lists.slice(middle)); return mergeTwoLists(left, right); } // 以return 的形式 简化 多个if判断 function mergeKLists(lists) { return lists.length === 0 ? null : lists.length === 1 ? lists[0] : lists.length === 2 ? mergeTwoLists(lists[0], lists[1]) : merge(lists); } module.exports = { mergeKLists: mergeKLists, };