23. 合并K个升序链表 Merge k Sorted Lists

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

 

方法一:顺序合并

类似于两个list合并

每次取一个list,依次顺序合并

public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) return null;
        ListNode ans = lists[0];
        for (int i = 1; i < lists.length; i++)
            ans = getMergeList( ans, lists[i]);
        return ans;

    }
    public ListNode getMergeList(ListNode l1,ListNode l2){
        ListNode dumpy = new ListNode(0);
        ListNode cur = dumpy;
        while (l1 != null && l2 != null){
            cur.next = l1.val <= l2.val ? l1 : l2;
            if (l1.val <= l2.val ) l1 = l1.next;
            else l2 = l2.next;
            cur = cur.next;
        }
        if( l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dumpy.next;
    }

 

 

 

方法二:分治合并

将list分成两组,然后再合并。递归进行

public ListNode mergeKLists(ListNode[] lists) {
        return merge(lists, 0, lists.length - 1);
    }
    public ListNode merge(ListNode[] lists, int l,int r){
        if( l == r) return lists[l];
        if(l > r) return null;
        int mid = (l + r) / 2;
        return mergeList(merge(lists, l ,mid ),merge(lists,mid + 1, r));
    }
    public ListNode mergeList(ListNode l1, ListNode l2){
        ListNode dumpy = new ListNode(0);
        ListNode cur = dumpy;
        while (l1 != null && l2 != null){
            cur.next = l1.val <= l2.val ? l1 : l2;
            if (l1.val <= l2.val ) l1 = l1.next;
            else l2 = l2.next;
            cur = cur.next;
        }
        if( l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dumpy.next;

    }

参考链接:

https://leetcode.com/problems/merge-k-sorted-lists/

https://leetcode-cn.com/problems/merge-k-sorted-lists/

posted @ 2020-12-07 17:58  diameter  阅读(94)  评论(0编辑  收藏  举报