leetcode 23.合并K个升序链表
采用以下循环的方式,运行时间过长,因此可以采取第二种方式:递归函数调用栈的方式
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
if (lists.length == 0) return null;
return mergeArr(lists);
};
// 采取循环的方式进行合并
function mergeArr(lists) {
if(lists.length == 1) return lists[0];
// 大于1
let head = merge(lists[0],lists[1]);
for (let i = 2; i < lists.length; i++) {
head = merge(head,lists[i]);
}
return head;
}
// 两个两个进行合并
function merge(lis1,lis2) {
if(lis1 == null && lis2 == null) return null;
if(lis1 == null && lis2 != null) return lis2;
if(lis1 != null && lis2 == null) return lis1;
let lis = null,head = null;
while(lis1 != null && lis2 != null) {
if (lis1.val < lis2.val) {
// 还没有头部
if(!head) {
lis = lis1;
head = lis1;
} else {
lis.next = lis1;
lis = lis.next;
}
lis1 = lis.next;
} else {
if (!head) {
lis = lis2;
head = lis2;
} else {
lis.next = lis2;
lis = lis.next;
}
}
}
// 查看是否还有多余的数据
lis.next = lis1 ? lis2 : lis1;
return head;
}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
if (lists.length === 0) return null;
return mergeArr(lists);
};
function mergeArr(lists) {
if (lists.length <= 1) return lists[0];
let index = Math.floor(lists.length / 2);
const left = mergeArr(lists.slice(0, index))
const right = mergeArr(lists.slice(index));
return merge(left, right);
}
function merge(l1, l2) {
if (l1 == null && l2 == null) return null;
if (l1 != null && l2 == null) return l1;
if (l1 == null && l2 != null) return l2;
let newHead = null, head = null;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
if (!head) {
newHead = l1;
head = l1;
} else {
newHead.next = l1;
newHead = newHead.next;
}
l1 = l1.next;
} else {
if (!head) {
newHead = l2;
head = l2;
} else {
newHead.next = l2;
newHead = newHead.next;
}
l2 = l2.next;
}
}
newHead.next = l1 ? l1 : l2;
return head;
}
533

被折叠的 条评论
为什么被折叠?



