leetcode 23-Merge k Sorted Lists(hard)

Posted yshi12

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 23-Merge k Sorted Lists(hard)相关的知识,希望对你有一定的参考价值。

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)的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

[LeetCode]23. Merge k Sorted Lists

leetcode23. Merge k Sorted Lists

leetCode 23. Merge k Sorted Lists

leetcode 23. Merge k Sorted Lists

LeetCode-23-Merge k Sorted Lists