归并方法,可与20题对照着看
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param lists ListNode类一维数组
* @return ListNode类
*/
function mergeKLists( lists ) {
// write code here
// let node = {
// val:null,
// next:null
// };
if (lists.length <= 1) return lists[0] || null;
return merge(lists, 0, lists.length-1);
}
function merge(lists, l, r) {
if (l > r) return null;
if (l === r) return lists[l];
const mid = Math.floor((l+r)/2);
return mergeTwoList(merge(lists, l, mid), merge(lists, mid+1, r));
}
function mergeTwoList (list1, list2) {
if (!list1 || !list2) return list1 || list2;
let p1 = list1, p2 = list2, head = {next: null}, p = head;
while(p1 && p2) {
if (p1.val > p2.val) {
p.next = p2;
p2 = p2.next;
} else {
p.next = p1;
p1 = p1.next;
}
p = p.next;
}
p.next = p1 || p2;
return head.next;
}
module.exports = {
mergeKLists : mergeKLists
};