LC23. Merge k Sorted Lists

Merge k Sorted Lists

Posted by freeCookie🍪 on December 28, 2016

LC23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list.

归并排序一大堆排序的链表。

Recursion Solution

先分成2个两个的再进行merge直到排序完毕。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        return partlize(lists, 0, lists.length-1);
    }
    
    private ListNode partlize(ListNode[] lists, int begin, int end){
        if(begin == end)    return lists[begin];
        if(begin > end) return null;
        int mid = begin + (end - begin)/2;
        ListNode l1 = partlize(lists, begin, mid);
        ListNode l2 = partlize(lists, mid+1, end);
        return merge(l1, l2);
    }
    
    private ListNode merge(ListNode l1, ListNode l2){
        if(l1 == null)  return l2;
        if(l2 == null)  return l1;
        if(l1.val < l2.val){
            l1.next = merge(l1.next, l2);
            return l1;
        }else{
            l2.next = merge(l2.next, l1);
            return l2;
        }
    }
}

O(nlgk). Partilize - lgk, Merge - n