码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 23-Merge k Sorted Lists(hard)

时间:2018-09-23 16:31:43      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:null   ==   public   linked   like   sorted   nod   example   OLE   

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

 

divide and conquer, like merge sort, use the dichotomy, divide the whole problem in half and half... first partition the list, than merge two list.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length==0) return null;
        return mergeKL(lists,0,lists.length-1);
    }
    public ListNode mergeKL(ListNode[] lists, int start, int end){
        if(start==end) return lists[start];
        int m=(start+end)/2;
        ListNode l1=mergeKL(lists, start, m);
        ListNode l2=mergeKL(lists, m+1, end);
        return merge(l1, l2);
    }
    public ListNode merge(ListNode l1, ListNode l2){
        ListNode head=new ListNode(0);
        ListNode node=head;
        while(l1!=null&&l2!=null){
            if(l1.val<l2.val){
                node.next=l1;
                l1=l1.next;
            }
            else{
                node.next=l2;
                l2=l2.next;
            }
            node=node.next;
        }
        if(l1==null) node.next=l2;
        else if(l2==null) node.next=l1;
        return head.next;
    }
}

 

leetcode 23-Merge k Sorted Lists(hard)

标签:null   ==   public   linked   like   sorted   nod   example   OLE   

原文地址:https://www.cnblogs.com/yshi12/p/9692758.html

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