给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 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 = [[]]
输出:[]
提示:
1/** 2 * Definition for singly-linked list. 3 * function ListNode(val, next) { 4 * this.val = (val===undefined ? 0 : val) 5 * this.next = (next===undefined ? null : next) 6 * } 7 */ 8/** 9 * @param {ListNode[]} lists 10 * @return {ListNode} 11 */ 12var mergeKLists = function(lists) { 13 14};
参考答案:
1/** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8/** 9 * @param {ListNode[]} lists 10 * @return {ListNode} 11 */ 12var mergeKLists = function(lists) { 13 if (lists.length === 0) return null; 14 return mergeArr(lists); 15}; 16function mergeArr(lists) { 17 if (lists.length <= 1) return lists[0]; 18 let index = Math.floor(lists.length / 2); 19 const left = mergeArr(lists.slice(0, index)) 20 const right = mergeArr(lists.slice(index)); 21 return merge(left, right); 22} 23function merge(l1, l2) { 24 if (l1 == null && l2 == null) return null; 25 if (l1 != null && l2 == null) return l1; 26 if (l1 == null && l2 != null) return l2; 27 let newHead = null, head = null; 28 while (l1 != null && l2 != null) { 29 if (l1.val < l2.val) { 30 if (!head) { 31 newHead = l1; 32 head = l1; 33 } else { 34 newHead.next = l1; 35 newHead = newHead.next; 36 } 37 l1 = l1.next; 38 } else { 39 if (!head) { 40 newHead = l2; 41 head = l2; 42 } else { 43 newHead.next = l2; 44 newHead = newHead.next; 45 } 46 l2 = l2.next; 47 } 48 } 49 newHead.next = l1 ? l1 : l2; 50 return head; 51}
最近更新时间:2024-08-10