23. Merge k Sorted Lists
Posted 暗影侠客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了23. Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
1 var mergeKLists = function(lists) { 2 3 var tempArry = [], listsLength; 4 5 //先剔除空列表 6 for (var i = 0; i < lists.length; ) { 7 if (lists[i]) { 8 i++; 9 } else { 10 lists.splice(i, 1); 11 } 12 } 13 if (lists.length === 0) return []; 14 15 //用一个队列来模拟,可以想象BFS的递推写法。 16 while (lists.length > 1) { 17 listsLength = lists.length; 18 if (listsLength % 2 !== 0) { 19 lists.push(null); 20 listsLength++; 21 } 22 for (var i = 0; i < listsLength; i += 2) { 23 tempArry.push(merge2Lists(lists[i], lists[i + 1])); 24 } 25 lists = tempArry; 26 tempArry = []; 27 } 28 return lists[0]; 29 30 function merge2Lists(list1, list2) { 31 var head = new ListNode(0), temp = head; 32 while (list1 && list2) { 33 if (list1.val < list2.val) { 34 temp.next = new ListNode(list1.val); 35 list1 = list1.next; 36 } else { 37 temp.next = new ListNode(list2.val); 38 list2 = list2.next; 39 } 40 temp = temp.next; 41 } 42 temp.next = list1 ? list1 : list2; 43 return head.next; 44 } 45 };
以上是关于23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章