码迷,mamicode.com
首页 > Web开发 > 详细

23. Merge k Sorted Lists(js)

时间:2019-02-16 13:49:26      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:nbsp   fun   lis   null   list   parse   var   output   style   

23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
题意:按大小顺序合并n条链表
代码如下:
/**
 * 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;
    var n=lists.length;
    while(n>1){
        var k=parseInt((n+1)/2);
        for(var i=0;i<parseInt(n/2);i++){
          lists[i]=  mergeTwoLists(lists[i],lists[i+k]);
        }
        n=k;
    }
    return lists[0];
};
var mergeTwoLists=function(list1,list2){
    var head=new ListNode(-1);
    var curr=head;
    while(list1 && list2){
        if(list1.val<list2.val){
            curr.next=list1;
            list1=list1.next;
        }else{
            curr.next=list2;
            list2=list2.next;
        }
        curr=curr.next;
    }
    if(list1) curr.next=list1;
    if(list2) curr.next=list2;
    return head.next;
}

 

23. Merge k Sorted Lists(js)

标签:nbsp   fun   lis   null   list   parse   var   output   style   

原文地址:https://www.cnblogs.com/xingguozhiming/p/10387376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!