23. 合并K个升序链表

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


分治思想。
为什么分治的判断条件是l==r 而快排是l>=r?原因在于传参:
分治是(l,mid),(mid+1,r)是连续的,而快排是:(l,j-1),(j+1,r);就会出现l>=r;举个例子:[1,2]排序,返回的j=0;进入到下一层就是(0,-1),(1,1);

    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0) {
            return null;
        }

        return divid(lists,0,lists.length - 1);

    }

    public ListNode divid(ListNode[] lists, int l, int r) {
        if(l==r) {
            return lists[l];
        }
        int mid = l+(r-l)/2;
        ListNode l1 = divid(lists,l,mid);
        ListNode l2 = divid(lists,mid+1,r);
        ListNode ret = merge(l1,l2);
        return ret;

    }

    public ListNode merge(ListNode l1, ListNode l2) {
        if(l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }

        ListNode dummyHead = new ListNode(-1);
        ListNode cur = dummyHead;

        while(l1 != null && l2 != null) {
           
           if(l1.val < l2.val) {
               cur.next = l1;
               cur = cur.next;
               l1 = l1.next;
           } else {
               cur.next = l2;
               cur = cur.next;
               l2 = l2.next;
           }
        }

        if(l1 != null) {
            cur.next = l1;
        }

        if(l2 != null) {
            cur.next = l2;
        }
        return dummyHead.next;
    }
posted @ 2022-02-25 20:23  一颗青菜  阅读(11)  评论(0)    收藏  举报